javascript - Javascript:从数组中随机选择多个元素(不是单个值选择)
问题描述
我正在尝试编写代码以从数组中选择 n 个随机元素。例如:
const originalArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const randomSelection = (n) => {
if (n > originalArray.length) {
return originalArray;
} else {
//Some Code to randomly select n elements from orignialArray
}
}
const newArray = randomSelection(2); //Random selection of 2 elements from the above array
实现这一目标的代码是什么?我搜索了案例,但想知道是否有更简单、更直接的方法来做到这一点。
有什么建议吗?提前非常感谢!
解决方案
此代码n
从数组中生成随机元素,并避免重复:
const originalArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const randomSelection = (n) => {
let newArr = [];
if (n >= originalArray.length) {
return originalArray;
}
for (let i = 0; i < n; i++) {
let newElem = originalArray[Math.floor(Math.random() * originalArray.length)];
while (newArr.includes(newElem)) {
newElem = originalArray[Math.floor(Math.random() * originalArray.length)];
}
newArr.push(newElem);
}
return newArr;
}
console.log(randomSelection(2));
console.log(randomSelection(5));
.as-console-wrapper { max-height: 100% !important; top: auto; }
如果您不关心重复项,请删除while
:
const originalArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const randomSelection = (n) => {
let newArr = [];
if (n >= originalArray.length) {
return originalArray;
}
for (let i = 0; i < n; i++) {
let newElem = originalArray[Math.floor(Math.random() * originalArray.length)];
newArr.push(newElem);
}
return newArr;
}
console.log(randomSelection(2));
console.log(randomSelection(5));
.as-console-wrapper { max-height: 100% !important; top: auto; }
推荐阅读
- java - 在java中的json对象中放入一个整数
- linux - 无法在 Linux (Xubuntu 18.04) 上使用 pyserial 读取/写入
- react-native-android - 如何使用 geolocation.getCurrentPosition && geolocation.watchPosition
- python - Schechter 函数:绘图
- drupal - Google 搜索显示的结果与元标记不同
- youtube-data-api - API调用中的YouTube搜索运算符?布尔运算符 AND、OR 和 NOT
- c# - 特定于应用程序的隔离 CngKey
- python - 如何删除项目由于列表的前一项字符
- sql - 带有 +00:00 部分的 ORACLE 日期格式
- android - 找不到 com.android.tools.build:aapt2:3.3.2-5309881