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

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

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

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay