Shuffle array

OSCC · JavaScript, Array, Random, Algorithm · Feb 20, 2021

Randomizes the order of the values of an array, returning a new array.

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  return arr;
const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]

Recommended snippets

  • Partition array

    JavaScript, Array

    Applies fn to each value in arr, splitting it each time the provided function returns a new value.

  • Finds the highest index at which a value should be inserted into an array in order to maintain its sort order, based on a provided iterator function.

  • Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.