2
Fisher Yates Shuffle
gerrit edited this page 2026-06-24 08:30:26 +00:00
/**
* Shuffles an array of objects using the Fisher-Yates algorithm.
* @param {Array<Object>} array - The target array of objects to shuffle.
* @returns {Array<Object>} A new, randomly shuffled array.
*/
function shuffleArrayOfObjects(array) {
// Create a shallow copy to prevent modifying the original array
const shuffled = [...array];
// Iterate backwards from the last element down to index 1
for (let i = shuffled.length - 1; i > 0; i--) {
// Pick a random index from 0 to i inclusive
const j = Math.floor(Math.random() * (i + 1));
// Swap elements at indices i and j
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}