Back to Snippets
CODE
Shuffle Array (Fisher-Yates Algorithm)
Description
Fair and unbiased array shuffling using the Fisher-Yates (Knuth) shuffle algorithm
Code
/**
* Shuffle array using Fisher-Yates (Knuth) algorithm
* @param arr Array to shuffle
* @returns New shuffled array (original remains unchanged)
*/
function shuffleArray<T>(arr: T[]): T[] {
const array = [...arr];
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// Usage Example
const numbers = [1, 2, 3, 4, 5];
const shuffled = shuffleArray(numbers);
console.log(shuffled); // Random order like [3, 1, 5, 2, 4]
console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)Usage
Perfect for randomizing quiz questions, game mechanics, or any scenario requiring fair randomization