Array shuffling utility using Fisher-Yates algorithm.
File: src/utils/functions/shuffle-array.ts
export const shuffleArray = <T>(array: T[]) => {
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;
};
The shuffleArray function randomly shuffles an array in-place using the Fisher-Yates (Knuth) shuffle algorithm.
Type Parameter:
T: The type of array elementsParameters:
array: The array to shuffle (modified in-place)Returns: The shuffled array (same reference as input)
Note: This function mutates the original array. If you need to preserve the original array, create a copy before shuffling.
The Fisher-Yates algorithm ensures uniform random distribution and is one of the most efficient shuffling algorithms.
Angular Material Dev UI (or Angular Material Blocks) is one place stop for developers to explore components and blocks for their Angular Material and Tailwind CSS based applications.
Find us on X (Twitter), LinkedIn, Instagram & Threads