How to Shuffle an Array in JavaScript? [Step-by-Step Guide]

Last updated

Written by yasmin

How to Shuffle an Array in JavaScript

In JavaScript many times we need to shuffle all the items in an array and in this article I going to teach you four simple methods to do this task. All the methods mentioned in this article are easy to understand and presented in a simple, step-by-step manner, to ensure that even a beginner can understand them easily.

1. Using “sort” with “Math.random”

functionshuffleArray(array){

return array.sort(() => Math.random()-0.5);

}

If you looking for a simple method that you can follow with just a few lines of code then you can use sort with the Math.random method.

First, create a normal function by passing an argument in it.

functionshuffleArray2(array){//passing "array" as a argument

}

Now, you need to apply the sort method on the “array” argument and sort it using random values generated by the Math.random() method.

functionshuffleArray2(array){

return array.sort(() => Math.random()-0.5); //sorting with random values

}

Now our function is ready to use, here is how can you use this function:

functionshuffleArray2(array){

return array.sort(() => Math.random()-0.5);

}

constnum=[1, 2, 3, 4, 5, 6, 7];

console.log("random num:", shuffleArray(num));

//Output

//random num: [2, 4, 6, 1, 5, 3, 7]

Also See: How to Convert String Array to Integer Array? [5 Easy Methods]

2. Using “map” and “sort” Method

functionshuffleArray(array){

return array

.map(value => ({value, sort: Math.random()}))

.sort((a, b) => a.sort- b.sort)

.map(({value}) => value);

}

Using the map and the sort methods you can easily shuffle an array in JavaScript, here is a step-by-step guide on how to do it:

First, create a regular function or an arrow function that takes “array” as an argument and returns it.

functionshuffleArray(array){//passing array as a argument

return array

}

Before returning the array you need to apply some methods to shuffle all the items within the array and you can easily do it by applying map and sort methods.

function shuffleArray(array) {

return array

.map(value => ({ value, sort: Math.random() })) //sort property holds a random number

}

In the above code, I’m assigning a random number to the sort property of each object, resulting in a unique value for every element.

Now you need to short the object according to the “sort” value in it with the sort method, here is how to do it:

functionshuffleArray(array){

return array

.map(value => ({value, sort: Math.random()}))

.sort((a, b) => a.sort- b.sort)//sorting object

}

Once the objects are sort we can return just the value using the map method.

functionshuffleArray(array){

return array
 .map(value => ({value, sort: Math.random()}))
 .sort((a, b) => a.sort- b.sort)
 .map(({value}) => value)//returning value

}

This function is now ready to use; simply pass the array as a parameter to shuffle the items within it.

functionshuffleArray(array){

return array
 .map(value => ({value, sort: Math.random()}))
 .sort((a, b) => a.sort- b.sort)
 .map(({value}) => value)
 }

constnum=[1, 2, 3, 4, 5, 6, 7];

console.log(shuffleArray(num));

//Output

//[4,5,3,7,2,6,1]

3. Using the Fisher-Yates (Knuth) Shuffle

Fisher–Yates shuffle algorithm

functionshuffleArray(array){

for(leti= array.length-1; i >0; i--){

constj= Math.floor(Math.random()*(i +1));

[array[i], array[j]]=[array[j], array[i]];

}

return array;

}

Fisher-Yates is a famous algorithm for shuffling a finite sequence, we can use this algorithm to shuffle items in an array.

Just copy the above Fisher-Yates function code and pass the array that you want to randomize.

functionshuffleArray(array){

for(leti= array.length-1; i >0; i--){

constj= Math.floor(Math.random()*(i +1));

[array[i], array[j]]=[array[j], array[i]];

}

return array;

}

constnum=[1, 2, 3, 4, 5, 6, 7];

//Output

[4, 2, 1, 5, 6, 3, 7]

4. Using a Temporary Array

functionshuffleArray3(array){

constshuffled=[];

while(array.length){

constrandomIndex= Math.floor(Math.random()* array.length);

shuffled.push(array.splice(randomIndex, 1)[0]);

}

return shuffled;

}

If you’re looking for a loop-based method to shuffle items in an array, then this while loop approach will be effective for you.

Define a function that takes an array as an argument such as “array”, and within that function, create a variable initialized to an empty array.

Use a while loop that runs as long as there are elements in the original array.

functionshuffleArray3(array){

constshuffled=[];

while(array.length){

}

}

Next, you need to generate a random index inside the loop using `Math.random()` to select a position within the array.

functionshuffleArray3(array){

constshuffled=[];

while(array.length){

constrandomIndex= Math.floor(Math.random()* array.length); //generate a random index

}

}

Use array.splice(randomIndex, 1) to remove the element at the random index from the array and add it to the shuffled array.

functionshuffleArray3(array){

constshuffled=[];

while(array.length){

constrandomIndex= Math.floor(Math.random()* array.length);

shuffled.push(array.splice(randomIndex, 1)[0]); //Remove and Store Element:

}

return shuffled;

}

Finally, return the shuffled array, which now contains the elements in a random order.

functionshuffleArray(array){

constshuffled=[];

while(array.length){

constrandomIndex= Math.floor(Math.random()* array.length);

shuffled.push(array.splice(randomIndex, 1)[0]);

}

return shuffled;

}

constnum=[1, 2, 3, 4, 5, 6, 7];

console.log(shuffleArray(num));

//Output

//[3,2,5,7,3,6,1]

Conclusion

There are several methods available in JavaScript to shuffle an array. I’ve shown you four simple techniques that anyone new to JavaScript can easily use.

If you have any questions about this or any other topics, please feel free to reach out to me. I’ll be happy to help!

Related Post:

Leave a Comment

Exit mobile version