1. Introduction
In this short article, we are going to present the easiest way to shuffle an array in JavaScript.
2. Shuffle function
To shuffle an array in JavaScript we can use
Math.random()
a function that returns a pseudo-random number in range 0-1. First, we iterate over the collection and for every value, we add a special random identifier, then we sort the output by that generated id. The last step is to get original values from the temporary array that contains a value with id.
const intList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stringList = ["green", "yellow", "black", "white", "orange"];
const shuffle = (array) => array.map(a => [Math.random(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
console.log(shuffle(intList));
console.log(shuffle(stringList));
3. Conclusion
In this article, we show how to shuffle the array in JavaScript. We used
Math.random()
method to add a pseudo-random index to each element and then sort items by that additional identifier.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}