In vanilla JavaScript, there is no direct way to randomize array elements. Although languages like PHP and Ruby provide built-in methods for shuffling arrays, JavaScript does not.
The most commonly used solution to randomize an array is the Fisher–Yates shuffle algorithm:
- Write down the numbers from 1 through N.
- Pick a random number k between one and the number of unstruck numbers remaining (inclusive).
- Counting from the low end, strike out the kth number not yet struck out, and write it down at the end of a separate list.
- Repeat from step 2 until all the numbers have been struck out.
- The sequence of numbers written down in step 3 is now a random permutation of the original numbers.
Here is a JavaScript function that implements the Fisher-Yates shuffle algorithm:
const shuffle = (array) => {
// loop all elements
for (let i = array.length - 1; i > 0; i--) {
// pickup a random element
const j = Math.floor(Math.random() * i);
const temp = array[i];
// swap it with the current element
array[i] = array[j];
array[j] = temp;
}
};
Now you can call the above function by passing in the array as an argument:
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒'];
// shuffle array
shuffle(fruits);
console.log(fruits);
// [ '🍓', '🍉', '🍒', '🍑', '🍇' ]
The above solution shuffles the original array and does not return a copy. If you want to keep the original array unchanged, use the Array.slice()
method to pass in a copy:
const fruits2 = fruits.slice();
shuffle(fruits2);
If you are already using Lodash in your project, just use the _.shuffle()
method to randomize an array. This method implements the same Fisher-Yates shuffle algorithm to shuffle array elements, and returns a new array:
const _ = require('lodash');
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒'];
// shuffle array
const shuffled = _.shuffle(fruits);
console.log(shuffled);
// [ '🍉', '🍒', '🍓', '🍇', '🍑' ]
Take a look this guide to learn more about JavaScript arrays and how to use them to store multiple values in a single variable.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.