Shuffle array

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]

More like this

  • JavaScript Algorithms

    Learn a handful of popular algorithms, implemented in JavaScript ES6.

    Collection · 35 snippets

  • Partition array

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

    JavaScript, Array · Oct 22, 2020

  • Array of successive values

    Applies a function to each element from left to right, returning an array of successively reduced values.

    JavaScript, Array · Oct 22, 2020

  • Insertion index in sorted array

    Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting order.

    JavaScript, Array · Oct 22, 2020