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"
function.js
function shuffleArray(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.
function
function shuffleArray2(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.
function.js
function shuffleArray2(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:
function.js
function shuffleArray2(array) {
return array.sort(() => Math.random() - 0.5);
}
const num = [1, 2, 3, 4, 5, 6, 7];
console.log("random num:", shuffleArray(num));
//Output
//random num: [2, 4, 6, 1, 5, 3, 7]
2. Using "map" and "sort" Method
function.js
function shuffleArray(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.
function.js
function shuffleArray(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:
function.js
function shuffleArray(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.
function.js
function shuffleArray(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.
function.js
function shuffleArray(array) {
return array
.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
}
const num = [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
function.js
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = 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.
function.js
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const num = [1, 2, 3, 4, 5, 6, 7];
//Output
[4, 2, 1, 5, 6, 3, 7]
4. Using a Temporary Array
function.js
function shuffleArray3(array) {
const shuffled = [];
while (array.length) {
const randomIndex = 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.
function.js
function shuffleArray3(array) {
const shuffled = [];
while (array.length) {
}
}
Next, you need to generate a random index inside the loop using `Math.random()
` to select a position within the array.
function.js
function shuffleArray3(array) {
const shuffled = [];
while (array.length) {
const randomIndex = 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.
function.js
function shuffleArray3(array) {
const shuffled = [];
while (array.length) {
const randomIndex = 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.
function.js
function shuffleArray(array) {
const shuffled = [];
while (array.length) {
const randomIndex = Math.floor(Math.random() * array.length);
shuffled.push(array.splice(randomIndex, 1)[0]);
}
return shuffled;
}
const num = [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:
- How to Check If a Number Is Even in JavaScript? [3 Methods]
- How to Disable HTML Code without Deleting [3 Methods]
Advertisement
Leave a comment 💬
All Comments
No comments yet.