N random elements in array

OSCC · JavaScript, Array, Random · Oct 22, 2020

Gets n random elements at unique keys from an array up to the size of the array.

  • Shuffle the array using the Fisher-Yates algorithm.
  • Use Array.prototype.slice() to get the first n elements.
  • Omit the second argument, n, to get only one element at random from the array.
const sampleSize = ([...arr], n = 1) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr.slice(0, n);
};
sampleSize([1, 2, 3], 2); // [3, 1]
sampleSize([1, 2, 3], 4); // [2, 3, 1]

Recommended snippets

  • Weighted sample

    JavaScript, Array

    Gets a random element from an array, using the provided weights as the probabilities for each element.

  • Random element in array

    JavaScript, Array

    Gets a random element from an array.

  • Value frequencies

    JavaScript, Array

    Creates an object with the unique values of an array as keys and their frequencies as the values.