Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize (shuffle) a JavaScript array?

I have an array like this:

var arr1 = ["a", "b", "c", "d"]; 

How can I randomize / shuffle it?

like image 708
Ali Avatar asked Mar 15 '10 22:03

Ali


People also ask

How do you randomize an array in JavaScript?

Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...

How do you random shuffle an array?

Shuffle Array using Random Class We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

Is there a shuffle method in JavaScript?

A JavaScript array elements can be shuffled by using the sort() method. The JavaScript Array sort() method is used to sort the elements of an array. The method accepts a comparison function and performs a sort based on the value returned by that function.


1 Answers

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

You can see a great visualization here (and the original post linked to this)

function shuffle(array) {   let currentIndex = array.length,  randomIndex;    // While there remain elements to shuffle...   while (currentIndex != 0) {      // Pick a remaining element...     randomIndex = Math.floor(Math.random() * currentIndex);     currentIndex--;      // And swap it with the current element.     [array[currentIndex], array[randomIndex]] = [       array[randomIndex], array[currentIndex]];   }    return array; }  // Used like so var arr = [2, 11, 37, 42]; shuffle(arr); console.log(arr);

Some more info about the algorithm used.

like image 133
20 revs, 16 users 36% Avatar answered Sep 22 '22 05:09

20 revs, 16 users 36%