w3docs logo
  1. Snippets
  2. JavaScript
  3. How to Randomize (shuffle) a JavaScript Array

How to Randomize (shuffle) a JavaScript Array

In contrary to languages like Ruby and PHP, JavaScript does not have an built-in method of shuffling the array. However, there is a method that allows shuffling the sequence. Let’s discuss a particular case.

For example, we have the following array:

let arr = [1, 2, 3, 4, 5]
=> [3, 5, 4, 1, 2] // a possible shuffle result

Shuffling an array of values is considered one of the oldest problems in computer science. Shuffling is possible with the Fisher-Yates shuffle algorithm for generating a random permutation of a finite sequence. That is to say, the algorithm shuffles the sequence.

Richard Durstenfeld introduces the modern version of the Fisher-Yates shuffle designed for computer use.

w3docs logo Javascript shufflig an array
function shuffleArray(array) { let curId = array.length; // There remain elements to shuffle while (0 !== curId) { // Pick a remaining element let randId = Math.floor(Math.random() * curId); curId -= 1; // Swap it with the current element. let tmp = array[curId]; array[curId] = array[randId]; array[randId] = tmp; } return array; } // Usage of shuffle let arr = [1, 2, 3, 4, 5]; arr = shuffleArray(arr); console.log(arr);

In case of coding with ES6/ECMAScript 2015, which allows assigning two variables immediately, the code will be shorter:

w3docs logo Javascript shufflig an array
function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } console.log(arr); } let arr = [1, 2, 3, 4, 5]; shuffleArray(arr);
w3docs logo Javascript shufflig an array
function shuffleArray(arr) { arr.sort(() => Math.random() - 0.5); } let arr = [1, 2, 3, 4, 5]; shuffleArray(arr); console.log(arr)

Arrays

The JavaScript array class is used in the construction of arrays, which are high-level and list-like objects. Arrays can be used for storing several values in a single variable. An array can be described as a unique variable that is capable of holding more than one value at the same time.

Each item has a number attached to it which is called a numeric index allowing you to access it. JavaScript arrays start at zero index and are manipulated with different methods.

Do you find this helpful?