首页 > 解决方案 > 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

实现这一目标的代码是什么?我搜索了案例,但想知道是否有更简单、更直接的方法来做到这一点。

有什么建议吗?提前非常感谢!

标签: javascriptarrays

解决方案


此代码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; }


推荐阅读