Open In App

How to Shuffle the Elements of an Array in JavaScript ?

Shuffling arrays is an elementary operation in programming that helps to introduce change into data sets. There are several approaches in JavaScript using which one can shuffle the elements of the array which are as follows:

Using Fisher-Yates (Knuth) shuffle

This algorithm, also known as the Knuth Shuffle, involves iterating through the array in reverse order and swapping each element with a randomly selected element that comes before it.

Example: The provided code uses the Fisher-Yates (Knuth) shuffle method to shuffle elements in a JavaScript array.






function fisherYatesShuffle(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]];
  }
  return arr;
}
 
const arr1 = [1, 2, 3, 4, 5];
const shuffledArr1 = fisherYatesShuffle([...arr1]);
console.log(shuffledArr1);

Output
[ 2, 4, 5, 1, 3 ]

Using sort with Math.random

The approach uses the `sort` function in combination with a custom comparison function which makes use of `Math.random()` for introducing randomness. When the array is effectively shuffled by subtracting random values, it is a result of the stability of the sorting algorithm.

Example: The sort with Math.random method is applied in the following code to shuffle elements in an array in JavaScript.




function shuffleArray(arr) {
  arr.sort(function (a, b) {
    return Math.random() - 0.5;
  });
}
let myArr = [1, 2, 3, 4, 5];
shuffleArray(myArr);
console.log(myArr);

Output
[ 1, 2, 4, 5, 3 ]

Using array.map with Math.random

This method shuffles an array effectively using Math.random(). The original value plus a randomly assigned number will be assigned as an element into an object in the `randomSort(array)` function. Sorting takes place depending on how much these numbers are randomly generated thereby leading to an array that is randomly sorted.

Example: The following code shuffles elements in a JavaScript array by using the array.map with Math.random method.




function randomSort(arr) {
  return arr
    .map((val) => ({ val, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(({ val }) => val);
}
 
const arr3 = [1, 2, 3, 4, 5];
const shuffledArr3 = randomSort([...arr3]);
console.log(shuffledArr3);

Output
[ 4, 5, 1, 3, 2 ]

Using array.reduce with Math.random

Shuffling elements in an array by array.reduce and Math.random(). These functions accumulate new shuffled arrays that then change their element with randomly generated indices iteratively for every element in them.Shuffle array using reduce (array) thus swaps input array elements randomly.

Example: The following code shuffles elements in a JavaScript array by using the array.reduce with Math.random method.




function rShuffle(a) {
  return a.reduce((acc, _, i, arr) => {
    const rI = Math.floor(Math.random() * (arr.length - i)) + i;
    [arr[i], arr[rI]] = [arr[rI], arr[i]];
    return arr;
  }, []);
}
 
const a4 = [1, 2, 3, 4, 5];
const sA4 = rShuffle([...a4]);
console.log(sA4);

Output
[ 5, 2, 4, 3, 1 ]

Using generator functions

This technique implements a generator function that uses the Fisher-Yates (Knuth) Shuffle algorithm to shuffle an array. At every stage, the generator produces copies of the array thus preventing alterations to the original one. This makes it possible to get intermediate shuffled versions and a final completely shuffled array.

Example: In the code below, elements are shuffled from a JavaScript array with the help of generator functions.




function* shuffleGen(arr) {
  let curIndex = arr.length,
    randIndex;
 
  while (curIndex !== 0) {
    randIndex = Math.floor(Math.random() * curIndex);
    curIndex--;
 
    [arr[curIndex], arr[randIndex]] =
        [arr[randIndex], arr[curIndex]];
 
    yield arr.slice();
  }
}
 
// Example usage:
const myArr = [1, 2, 3, 4, 5];
const shuffler = shuffleGen(myArr);
 
for (const sArr of shuffler) {
  console.log(sArr);
}
 
const finalSArr = myArr;
console.log(`Final shuffled array: ${finalSArr}`);

Output
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 4, 3, 5 ]
[ 4, 2, 1, 3, 5 ]
[ 4, 2, 1, 3, 5 ]
[ 4, 2, 1, 3, 5 ]
Final shuffled array: 4,2,1,3,5

Article Tags :