Languages
[Edit]
EN

JavaScript - sort in random order

7 points
Created by:
telsa
502

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]

 

References

  1. Fisher–Yates shuffle - Wikipedia

Alternative titles

  1. JavaScript - random array order
  2. JavaScript - shuffle array
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.

JavaScript - random

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