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:
xxxxxxxxxx
1
array.sort(() => Math.random() - 0.5);
Warning:
Array
sort()
method changes input array items order.
xxxxxxxxxx
1
const sortRandomly = (array) => array.sort(() => Math.random() - 0.5);
2
3
4
// Usage example:
5
6
const array = [1, 2, 3, 4, 5];
7
8
console.log(array); // [1, 2, 3, 4, 5]
9
sortRandomly(array); // <----- random sort function call
10
console.log(array); // [3, 4, 5, 2, 1]
The below example implements Fisher–Yates shuffle algorithm:
xxxxxxxxxx
1
const randomInteger = (max) => {
2
return Math.floor(max * Math.random());
3
};
4
5
const sortRandomly = (array) => {
6
for (let i = array.length - 1; i > 0; --i) {
7
const j = randomInteger(i + 1);
8
const tmp = array[i];
9
array[i] = array[j];
10
array[j] = tmp;
11
}
12
};
13
14
15
// Usage example:
16
17
const array = [1, 2, 3, 4, 5];
18
19
console.log(array); // [1, 2, 3, 4, 5]
20
sortRandomly(array); // <----- random sort function call
21
console.log(array); // [3, 4, 5, 2, 1]