This practical article walks you through 3 different approaches to shuffling a given array in Javascript.
Table of Contents
Using Sort() Function
You can shuffle an array by generating random numbers and comparing them in the sort() function.
Example:
const arr = ['dog', 'cat', 'dragon','slingacademy.com', 'banana'];
const shuffledArr = arr.sort(() => Math.random() - 0.5);
console.log(shuffledArr);
The Math.random() function generates a random number between 0 and 1 (inclusive of 0 but exclusive of 1). When we subtract 0.5 from this random number, we get a new random number that can be positive or negative, with an equal probability of being either.
Output:
[ 'cat', 'dog', 'slingacademy.com', 'banana', 'dragon' ]
The output will likely change each time you execute the code
Using For Loop
In this approach, we will iterate over the array in reverse order and swap each element with a randomly selected element from the range of unshuffled elements.
Example:
const arr = ['dog', 'cat', 'dragon', 'slingacademy.com', 'banana'];
// define a function that can be reused
const shuffleArray = (array) => {
// create a copy of the array so that the original array is not mutated
const newArray = [...array];
for (let i = newArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArray[i], newArray[j]] = [newArray[j], newArray[i]];
}
return newArray;
};
// use the function
const shuffledArray = shuffleArray(arr);
console.log(shuffledArray);
Output:
[ 'slingacademy.com', 'cat', 'banana', 'dragon', 'dog' ]
Using Lodash
Lodash is a super popular multi-purpose Javascript open-source library. You can add it to your project by running:
npm i lodash
And use the shuffle() function of lodash to get the job done quickly:
import _ from 'lodash'
const arr = [1, 2, 3, 4, 5]
const shuffleArr = _.shuffle(arr)
console.log(shuffleArr)
Output:
[ 5, 1, 2, 3, 4 ]