shuffleArr
Shuffles the elements of an array.
1. Code
const shuffleArr = <T>(arr: T[]) => {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
};
export default shuffleArr;
2. Installation
npx @jrtilak/lazykit@latest add shuffleArr -undefined
3. Description
The shuffleArr function is a utility function in JavaScript that takes an array and shuffles it. The function uses the Fisher-Yates algorithm to shuffle the array. The Fisher-Yates algorithm is an efficient algorithm for generating a random permutation of a finite sequence. The function returns a new array with the elements of the original array shuffled.
The shuffleArr function does not modify the original array, it returns a new array with the elements shuffled.
4. Props
Prop
Type
Default Value
arr*any[]---
5. Examples
import shuffleArr from ".";
const arr = [1, 2, 3, 4, 5];
const shuffledArr = shuffleArr(arr);
console.log(shuffledArr);
// Expected output: shuffled array of given array