AI solution for JavaScript Coding Question on BFE.dev
8. can you shuffle() an array?
One possible implementation of the shuffle() function is the Fisher-Yates shuffle algorithm:
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
This algorithm works by iterating through the array from the end to the beginning, and for each element i, randomly selecting an index j between 0 and i, and swapping the elements at positions i and j. This ensures that each element will have the same probability of being placed in any position, and thus generates a random permutation of the array.
To use it, simply pass an array to the function, like this:
const arr = [1, 2, 3, 4]
shuffle(arr)
console.log(arr) // prints a randomly shuffled permutation of the array
Note that the function modifies the array in place, so there's no need to assign the result to a new variable. Also, since the function is using Math.random() to generate the random indices, it's important to set a seed at the beginning of the program if we want the results to be reproducible.