How to Randomize (shuffle) a JavaScript Array
Arrays
The JavaScript array class is used to construct arrays, which are high-level and list-like objects. Arrays can be used for storing several values in a single variable. An array can be described as a unique variable that is capable of holding more than one value at the same time.
Each item has a number attached to it which is called a numeric index allowing you to access it. JavaScript arrays are manipulated with different methods.
As the following example suggests, we have a fruits array that consists of 4 elements and can be targeted by their index, starting from 0.
const fruits = ["apple", "orange", "banana", "coconut"];
alert( fruits[0] ); // apple
alert( fruits[1] ); // orange
alert( fruits[2] ); // banana
alert( fruits[2] ); // coconut
In contrary to languages like Ruby and PHP, JavaScript does not have an built-in method of shuffling the array. However, there is a method that allows shuffling the sequence. Let’s discuss a particular case.
For example, we have the following array:
let arr = [1, 2, 3, 4, 5]
=> [3, 5, 4, 1, 2] // a possible shuffle result
As the first example, we will define a function called randomize, which will take a parameter that is the array we want to shuffle. Then, we get a random index on each call and swap the elements' locations with each other, returning the values at the end.
Shuffling an array of values is considered one of the oldest problems in computer science. Shuffling is possible with the Fisher-Yates shuffle algorithm for generating a random permutation of a finite sequence. That is to say, and the algorithm shuffles the sequence.
We can implement the algorithm with a for loop compared to the first example.
Richard Durstenfeld introduces the modern version of the Fisher-Yates shuffle designed for computer use.
As the last example, we can also use the built-in javascript sort function to get the array sorted randomly on each call, which is much cleaner: