263 words
1 minutes
How to Shuffle Arrays in JavaScript
Shuffling arrays in JavaScript can be efficiently done using the Fisher-Yates (or Knuth) shuffle algorithm. This algorithm ensures a uniform random shuffle and operates in linear time, O(n), making it suitable for shuffling arrays of any size. Here’s how you can implement it:
Fisher-Yates Shuffle Algorithm
- Initialize: Start with the last element of the array.
- Swap: For each element, swap it with a randomly chosen element that comes before or at the current position.
- Repeat: Continue this process until the first element is reached.
Code Example
Here’s a concise implementation of the Fisher-Yates shuffle algorithm in JavaScript:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
// Generate a random index from 0 to i
const j = Math.floor(Math.random() * (i + 1));
// Swap elements at indices i and j
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// Example usage:
const myArray = [1, 2, 3, 4, 5];
console.log("Original array:", myArray);
const shuffledArray = shuffleArray(myArray);
console.log("Shuffled array:", shuffledArray);
Explanation
- Loop: The loop runs from the end of the array (
array.length - 1
) down to the beginning (0
). - Random Index:
Math.random() * (i + 1)
generates a random number between0
andi
, andMath.floor()
ensures it’s an integer. - Swap: The destructuring assignment
[array[i], array[j]] = [array[j], array[i]]
swaps the elements at indicesi
andj
.
Key Points
- Uniformity: The Fisher-Yates shuffle algorithm guarantees that every permutation of the array is equally likely.
- Efficiency: It runs in O(n) time complexity, which is optimal for shuffling arrays.
- In-place: This algorithm shuffles the array in place without requiring extra space.
Feel free to use and modify this implementation as needed for your projects!