DEV Community

Areeb ur Rub
Areeb ur Rub

Posted on

Randomly Sort Array in just one line;

Yesterday I was working on a JavaScript game and found this pretty cool and easy way to sort a Array randomly.

for this I use the .sort() function of Javascript


.sort() is a function in javascript which usually sort the array on the basis of the String value in ascending order by default.

but it can be changed using a compare function inside parameters.

how to Randomize Array

const NumArray = ['one','two','three'];
NumArray.sort(() => 0.5 - Math.random());

Basically, how compare function works is when it take two positions from array and put them into the function if it returs positve value don't change the order and vice versa.

so here Math.random(); give between 0 to 1 and its subtracted from 0.5 .

sum up

We use sort() function, Inside sort we put a compare function which is have chances to return postive or negetive number 50/50 and thats how we are getting random sorted Array

Top comments (1)

fkereki profile image
Federico Kereki

This is a very bad shuffling method -- please look at for the explanation, and for an alternative sort-based one-liner version that works well.