EN
TypeScript - sort in random order
0
points
In this short article, we would like to show how to sort array items in random order in TypeScript.
Quick solution:
const sortRandomly = (array: number[]): void => {
array.sort(() => (Math.random() < 0.5 ? +1 : -1));
};
// Usage example:
const array: number[] = [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:
const randomInteger = (max: number): number => {
return Math.floor(max * Math.random());
};
const sortRandomly = (array: number[]): void => {
for (let i = array.length - 1; i > 0; --i) {
const j = randomInteger(i);
const tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
};
// Usage example:
const array: number[] = [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