DEV Community

Cover image for Simple snippet to shuffle array
Gabriel Rufino
Gabriel Rufino

Posted on

Simple snippet to shuffle array

If you need to shuffle the elements of an array, you can use this simple function:

function shuffle(array) {
  const copy = [...array]

  return copy.sort(() => Math.random() - 0.5)
}
Enter fullscreen mode Exit fullscreen mode

The algorithm

  1. Creates a copy of the parameter to not modify the original array
  2. Uses the function Array.prototype.sort of the copy to randomly sort the array with a callback that always returns Math.random() - 0.5 (The random factor).

Example

const example = [1, 2, 3]

const shuffled = shuffle(example)

/*
  shuffled is one of these:
  - [1, 2, 3]
  - [1, 3, 2]
  - [2, 1, 3]
  - [2, 3, 1]
  - [3, 1, 2]
  - [3, 2, 1]
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
bravemaster619 profile image
bravemaster619

WARNING why you shouldn't use this method in cryptographic functions: javascript.info/task/shuffle

That somewhat works, because Math.random() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.

But because the sorting function is not meant to be used this way, not all permutations have the same probability.

Collapse
 
pentacular profile image
pentacular

It also breaks down when there are key collisions.

Sorting by non-unique keys is not shuffling.

Fisher-Yeats is trivial to implement and theoretically correct -- use that instead.

Collapse
 
gabrielrufino profile image
Gabriel Rufino

Thanks for contribute. 🙂