高级前端
手写代码
【Q677】如何实现一个 sampleSize 函数,从数组中随机取N个元素

如何实现一个 sampleSize 函数,从数组中随机取N个元素

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 696 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5);
const sampleSize = (list, n) => shuffle(list).slice(0, n);

Author 回答者: voezy (opens in a new tab)

Array.prototype.sampleSie = function (size) {
  const result = [];
  const tmp = [...this];
  const len = tmp.length;
  for (let i = 0; i < size && i < len; i++) {
    const index = Math.floor(Math.random() * tmp.length);
    result[i] = tmp.splice(index, 1)[0];
  }
  return result;
};

Author 回答者: rujptw (opens in a new tab)

不知道这样可不可以,从随机挑选的数,组成的数组,长度达到size,就返回

function sampleSize(array,size){
  let len = array.length,i,pickArr = [];
  while(len&&size){
    i = Math.floor(Math.random()*len);
    len--;
    pickArr.push(array.splice(i,1)[0]);
    size--;
  }
  return pickArr
}