从javascript

时间:2018-10-05 11:06:18

标签: javascript arrays typescript

我有一个看起来像这样的对象数组:

[
    {
      pVerb: "ask somebody out",
      meaning: "invite on a date"
    },
    {
      pVerb: "ask around",
      meaning: "ask many people the same question"
    },
    {
      pVerb: "add up to something",
      meaning: "equal"
    },
    {
      pVerb: "back something up",
      meaning: "reverse"
    },
    {
      pVerb: "back somebody up",
      meaning: "support"
    },
    {
      pVerb: "blow up",
      meaning: "explode"
    }
  ]

我需要遍历每个对象并生成较小的数组块,该块应该:

  1. 长度为3
  2. 包含pVerb的当前对象条目
  3. 置于随机位置

类似以下内容:

[
  [
    "!ask somebody out!",
    "add up to something",
    "back something up"
  ],
  [
    "add up to something",
    "!ask around!",
    "blow up"
  ],
  [
    "blow up",
    "back somebody up",
    "!add up to something!"
  ]
]

目前,我有类似的内容,但它不会检查重复的条目或将位置随机化:

const randomNumber = (max: number, min: number) => {
      const num = Math.floor(Math.random() * (max - min + 1)) + min;
      return num;
    };

    const array: any[] = [];
    for (const n of array) {
      array.push([
        n.meaning,
        array[randomNumber(0, array.length)]
          .meaning,
        array[randomNumber(0, array.length)]
          .meaning
      ]);
    }

TL:DR

我需要块数组,其中一个块将是[pVerb of first object, any other two pVerbs from any other two objects(unique)],下一个块将具有[pVerb of second object, ...]等。

1 个答案:

答案 0 :(得分:1)

借助随机播放,您可以从数组中随机选择三个元素:

const partialShuffle = (values, count) => {
  for (let i = 0; i < count; i++) {
    const j = Math.floor(Math.random() * (values.length - i)) + i;
    [values[i], values[j]] = [values[j], values[i]];
  }
};

const nums = [1, 2, 3, 4, 5, 6];
partialShuffle(nums, 3);
console.log('' + nums.slice(0, 3));
partialShuffle(nums, 3);
console.log('' + nums.slice(0, 3));
partialShuffle(nums, 3);
console.log('' + nums.slice(0, 3));

现在,在数组中有三个随机值,您需要确保其中一个是当前值–与pVerb相对应的一个。检查它是否在那里。

  • 如果已经存在,则无需执行其他操作。
  • 如果不存在,请随机选择一个物品替换它。
const randomTripleIncluding = (values, value) => {
  partialShuffle(values, 3);
  const triple = values.slice(0, 3);

  if (!triple.includes(value)) {
    triple[Math.floor(Math.random() * 3)] = value;
  }

  return triple;
};

这会弄乱数组的顺序,因此,由于要遍历原始数组,因此您将希望专门为混排使用制作一个副本。全部说明,类型:

const partialShuffle = (values: any[], count: number) => {
  for (let i = 0; i < count; i++) {
    const j = Math.floor(Math.random() * (values.length - i)) + i;
    [values[i], values[j]] = [values[j], values[i]];
  }
};

const randomTripleIncluding = <T>(values: T[], value: T): T[] => {
  partialShuffle(values, 3);
  const triple = values.slice(0, 3);

  if (!triple.includes(value)) {
    triple[Math.floor(Math.random() * 3)] = value;
  }

  return triple;
};

const input = [
  {pVerb: "ask somebody out", meaning: "invite on a date"},
  …
];

const scratchInput = input.slice();

const result = input.map(n => randomTripleIncluding(scratchInput, n));