Languages
[Edit]
EN

JavaScript - sort in random order

4 points
Created by:
telsa
352

In this short article, we would like to show how to sort array items in random order in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const sortRandomly = array => {
   array.sort(() => Math.random() < 0.5 ? +1 : -1);
};

// Usage example:

const array = [1, 2, 3, 4, 5];

console.log(array);  // 1, 2, 3, 4, 5
sortRandomly(array);
console.log(array);  // 3, 4, 5, 2, 1

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