EN
JavaScript - sort in random order
7
points
In this short article, we would like to show how to sort array items in random order in JavaScript.
Quick solution:
array.sort(() => Math.random() - 0.5);
Warning:
Array
sort()
method changes input array items order.Â
Â
Reusable function
// ONLINE-RUNNER:browser;
const sortRandomly = (array) => array.sort(() => Math.random() - 0.5);
// Usage example:
const array = [1, 2, 3, 4, 5];
console.log(array); // [1, 2, 3, 4, 5]
sortRandomly(array); // <----- random sort function call
console.log(array); // [3, 4, 5, 2, 1]
Â
Fisher–Yates shuffle algorithm
The below example implements Fisher–Yates shuffle algorithm:
// ONLINE-RUNNER:browser;
const randomInteger = (max) => {
return Math.floor(max * Math.random());
};
const sortRandomly = (array) => {
for (let i = array.length - 1; i > 0; --i) {
const j = randomInteger(i + 1);
const tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
};
// Usage example:
const array = [1, 2, 3, 4, 5];
console.log(array); // [1, 2, 3, 4, 5]
sortRandomly(array); // <----- random sort function call
console.log(array); // [3, 4, 5, 2, 1]
Â