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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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.

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay