How to Shuffle the Elements of an Array in JavaScript?
Last Updated :
17 Nov, 2024
Shuffle an array means randomly change the order of array elements. This is useful for creating random arrangements, like shuffling a deck of cards or randomizing a list. There are different wats to shuffle the elements of an array in JavaScript:
1. 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.
JavaScript
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 arr = [1, 2, 3, 4, 5];
const shuffledArr = fisherYatesShuffle([...arr]);
console.log(shuffledArr);
2. Using sort() with Math.random() Methods
The approach uses the sort() method 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.
JavaScript
function shuffleArray(arr) {
arr.sort(function (a, b) {
return Math.random() - 0.5;
});
}
let arr = [1, 2, 3, 4, 5];
shuffleArray(arr);
console.log(arr);
3. Using array.map() with Math.random() Methods
This method shuffles an array effectively using Math.random() method. 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.
JavaScript
function randomSort(arr) {
return arr
.map((val) => ({ val, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ val }) => val);
}
const arr = [1, 2, 3, 4, 5];
const shuffledArr = randomSort([...arr]);
console.log(shuffledArr);
4. Using array.reduce() with Math.random() Method
Shuffling elements in an array by array.reduce() and Math.random() method. These functions accumulate new shuffled arrays and 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.
JavaScript
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 arr = [1, 2, 3, 4, 5];
const suffelArr = rShuffle([...arr]);
console.log(suffelArr);
5. Using Generator Function
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.
JavaScript
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();
}
}
const arr = [1, 2, 3, 4, 5];
const shuffler = shuffleGen(arr);
for (const sArr of shuffler) {
console.log(sArr);
}
const finalSArr = arr;
console.log(`Final shuffled array: ${finalSArr}`);
Output[ 1, 2, 3, 4, 5 ]
[ 4, 2, 3, 1, 5 ]
[ 4, 3, 2, 1, 5 ]
[ 3, 4, 2, 1, 5 ]
[ 3, 4, 2, 1, 5 ]
Final shuffled array: 3,4,2,1,5
Similar Reads
How to Sort an Array Based on the Length of Each Element in JavaScript? Imagine you have a list of words or groups of items, and you want to arrange them in order from shortest to longest. This is a pretty common task in JavaScript, especially when working with text or collections of things. By sorting your list in this way, you can make sense of your data and make it e
3 min read
How to Shuffle an Array using JavaScript ? To shuffle a JavaScript array we can use the Fisher-Yates shuffle also known as knuth shuffle. It will sort the given array in a random order with the help of the math.random() function.1. Shuffle JavaScript Array Using Fisher-Yates ShuffleThe Fisher-Yates Shuffle iterates through the array in rever
3 min read
JavaScript - How to Remove an Element from an Array? Removing elements from an array is a fundamental operation in JavaScript, essential for data manipulation, filtering, and transformation. This guide will explore different methods to efficiently remove elements from an array, enhancing your understanding and capability in handling arrays.1. Using po
3 min read
How to create an array containing non-repeating elements in JavaScript ? In this article, we will learn how to create an array containing non-repeating elements in JavaScript.The following are the two approaches to generate an array containing n number of non-repeating random numbers.Table of ContentUsing do-while loop and includes() MethodUsing a set and checking its si
2 min read
JavaScript - Select a Random Element from JS Array Selecting a random element from array in JavaScript is done by accessing an element using random index from the array. We can select the random element using the Math.random() function.How to select a random element from an array in JavaScript?1. Using Math.random() MethodThe Math.random() method is
2 min read
JavaScript - Insert Element in an array In JavaScript elements can be inserted at the beginning, end, and at any specific index. JS provides several methods to perform the operations.At the Beginning This operation inserts an element at the start of the array. The unshift() method is commonly used, which mutates the original array and ret
2 min read