DEV Community

Areeb ur Rub
Areeb ur Rub

Posted on

2 2

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()

.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());
console.log(NumArray);

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
fkereki profile image
Federico Kereki

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

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay