How to Shuffle an Array using JavaScript ?
Last Updated :
15 Jul, 2025
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 Shuffle
The Fisher-Yates Shuffle iterates through the array in reverse order and swapping each element with a randomly selected element that comes before it.
Syntax
for (let i = array.length - 1; i > 0; i--) {
// Generate random index
const j = Math.floor(Math.random() * (i + 1));
// Swap elements at indices i and j
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
JavaScript
// Given array
const a = [10, 20, 30, 40, 50, 60, 70];
// Function to apply the Fisher-Yates Shuffle
function myFunction(array) {
// Iterate over the array in reverse order
for (let i = array.length - 1; i > 0; i--) {
// Generate Random Index
const j = Math.floor(Math.random() * (i + 1));
// Swap elements
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// Get the shuffled array from the function
const a1 = myFunction(a);
// Display Shuffled array
console.log("Shuffled Array: ", a1);
OutputShuffled Array: [
20, 30, 40, 50,
60, 70, 10
]
2. Using JavaScript array.sort() Method
We can use JavaScript array sort() method with a custom comparision function that generates a shuffled array. Passing a function that returns (random value - 0.5 ) as a comparator to sort() function.
Syntax
array.sort( () => Math.random()-0.5 );
JavaScript
// Given array
const a = [10, 20, 30, 40, 50, 60, 70];
// Shuffle the array using reduce() and
// math.random() methods
a.sort(() => Math.random() - 0.5);
// Display the shuffled array in the console
console.log("Shuffled Array: ", a);
OutputShuffled Array: [
60, 50, 70, 40,
30, 20, 10
]
3. Using array.reduce() with Math.random() Method
The array.reduce() method is used to return a single output after implementing the logic for all the elements. We can use the math.random() method to shuff the elements on each iteration in reduce method.
Syntax
array.reduce(
function(total, currentValue, currentIndex, arr),
initialValue
)
JavaScript
// Given array
const a = [10, 20, 30, 40, 50, 60, 70];
// Shuffle the array using reduce() and
// math.random() methods
const a1 = a.reduce(
(acc, _, i) => {
// Generate a random index
const random = Math.floor(Math.random() * (acc.length - i)) + i;
// Swap the element with random index element
[acc[i], acc[random]] = [acc[random], acc[i]];
return acc;
},
[...a] // Initialize accumulator as shoallow copy of given array
);
// Display the shuffled array in the console
console.log("Shuffled Array: ", a1);
OutputShuffled Array: [
60, 10, 50, 30,
40, 20, 70
]
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics