我有一个包含 700 个问题对象的数组,如下所示:
[
{
_id: "5ca3216579a592b0910f70d4"
question: "Who wrote Twilight series of novels?"
answer: "Stephenie Meyer"
category: "Art and Literature"
},
...
]
我还有一组 3 个选定的问题类别,如下所示:
["Art and Literature", "Music", "History"]
我基本上需要的是每个问题类别的 4 个随机问题。 所以:
- 4 道艺术和文学的随机问题
- 4 个随机的音乐问题
- 4 道历史随机题
理想情况下,我认为最好根据这 3 个类别将 12 个随机问题 ID 设置在一个新数组中,这样我就可以将它们发送到我的数据库中。
这是怎么做到的?
最佳答案
您应该首先为每个类别创建一系列问题,以便从中随机选择。
const art = arr.filter(question => question.category === 'Art and Literature');
const music = arr.filter(question => question.category === 'Music');
const history = arr.filter(question => question.category === 'History');
现在,只需为每个类别数组随机选择项目四次。
const categoryArrays = [art, music, history];
const results = [] // to store the selected ids
for (i = 0, i < 3, i++) { // To iterate over the three categories
for (j = 0, j < 4, j++) { // To select four times
results.push(categoryArrays[i][Math.floor(Math.random() * categoryArrays[i].length)]._id);
}
}
关于javascript - 如何根据匹配参数从数组中选择几个随机 id 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55512355/