Languages
[Edit]
EN

TypeScript - sort in random order

0 points
Created by:
Selina-Miranda
737

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

References

  1. Fisher–Yates shuffle - Wikipedia

Alternative titles

  1. TypeScript - random array order
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join