我想从初始数组中获取数组随机元素

我有一个初始array1 =[{id:"0",a:"4",b:"6"},{id:"1",a:"r",b:"8"},{id:"2",a:"8",b:"9"}] 我想要另一个包含来自初始数组的随机元素的数组

randomArray=[{id:"0",a:"4",b:"6"},{id:"2",a:"8",b:"9"}]

我该怎么做?


幕布斯7119047
浏览 175回答 2
2回答

一只斗牛犬

您可以在下面使用Array.prototype.filter和Math.random()喜欢;const array1 =[{id:"0",a:"4",b:"6"},{id:"1",a:"r",b:"8"},{id:"2",a:"8",b:"9"}];const filtered = array1.filter(() => Math.random() > 0.5);console.log(filtered);注意:在我的解决方案中,选择每个单独项目的概率为 50%。

慕森卡

const random = (array, length) => array.sort(() => 0.5 - Math.random()).slice(0, length);const mock = [  { id: "0", a: "4", b: "6" },  { id: "1", a: "r", b: "8" },  { id: "2", a: "8", b: "9" },  { id: "3", a: "8", b: "9" }];console.log(random(mock, 2))console.log(random(mock, 3))console.log(random(mock, 4))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript