简体   繁体   English

如何从二维数组中获取随机元素?

[英]How to get random elements from a 2 dimensional array?

If I have an 2 dimensional array and the number of elements in each row is different.如果我有一个二维数组并且每行中的元素数不同。 How i can get random elements from this array?我如何从这个数组中获取随机元素? Does anyone have a best solution?有没有人有最好的解决方案?

arr = [
 [2,3,4],
 [3,4]
 [1,22,3,45]
]

Use Array.flat() to flatten the input array and get the random element.使用Array.flat()将输入数组展平并获取随机元素。

 const arr = [ [2,3,4], [3,4], [1,22,3,45] ]; const flattenArr = arr.flat(); const randomIndex = Math.floor(Math.random()*flattenArr.length); console.log(flattenArr[randomIndex]);

 const arr = [ [2, 3, 4], [3, 4], [1, 22, 3, 45], ]; const flatArray = arr.reduce((acc, curr) => { return [...acc, ...curr]; }, []); function getRandomNumber(len) { return Math.floor(Math.random() * len); } const randomNumber = getRandomNumber(flatArray.length); console.log(flatArray[randomNumber]);

You can get a random index between 0 and the nested array length, try this:你可以得到一个介于 0 和嵌套数组长度之间的随机索引,试试这个:

 let arr = [ [2,3,4], [3,4], [1,22,3,45] ] let result = []; for(let i = 0; i < arr.length; i++){ result.push(arr[i][Math.floor(Math.random() * arr[i].length + 0)]); } console.log(result);

Try this尝试这个

 var arr = [ [2,3,4], [3,4], [1,22,3,45] ] flatArr=arr.flatMap(x=>x) console.log(flatArr[Math.floor(Math.random() * flatArr.length)]);

Using Math.random() to generate integers between 0 (inclusive) and length of sub array (exclusive).使用 Math.random() 生成 0(包括)和子数组长度(不包括)之间的整数。

 const numbers = [ [2, 3, 4], [3, 4], [1, 22, 3, 45], ]; const result = numbers.map( (_, i, arr) => arr[i][~~(Math.random() * arr[i].length)] ); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM