Gabriel Rufino
Gabriel Rufino's Blog

Gabriel Rufino's Blog

Simple snippet to shuffle array

Simple snippet to shuffle array

Gabriel Rufino's photo
Gabriel Rufino
·Jul 24, 2020·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

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)
}

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]
*/
 
Share this