Shuffle an Array
Darren Jones
April 27, 2021
There isn’t a `shuffle()` method for arrays. This function will return a copy of the array with the elements randomly shuffled:
javascript
const shuffle = array => {
const newArray = [...array];
for(let i = newArray.length-1,r;i;i--){
r = Math.floor((Math.random()*i));
[newArray[i],newArray[r]] = [newArray[r],newArray[i]];
}
return newArray
}
const food = ['🍏','🍌','🥕','🍩'];
const mixedFood = shuffle(food);
This uses the Fisher-Yates shuffle algorithm. This ensures that every combination of elements has an equally likely chance of being returned. It starts by making a copy of the array using the spread operator. It then starts with the last element in the array and swaps it with a random element before it, then it moves to the second-to-last element and swaps it with a random element that comes before it. The process continues until it reaches the beginning of the array. Destructuring is used to swap the elements over without creating a temporary variable.