我有一个对象数组,如下所示:
[
{
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"
}
]
我需要迭代每个对象并生成更小的数组块,应该:
如下所示:
[
[
"!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
]);
}
我需要一大块的块,其中一个块将是[pVerb of first object, any other two pVerbs from any other two objects(unique)]
下一个块将有[pVerb of second object, ...]
等。
您可以在shuffle的帮助下从数组中随机选择三个元素:
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));