How to Shuffle Elements of an Array in JavaScript
Table of Contents
In most contexts, the order of an array is important and in that order for a reason.
However, in other contexts, you want to randomize, or shuffle the elements in an array to give each element a new spot in the array.
In this post, we'll learn the easiest way to shuffle elements of an array in JavaScript.
How to shuffle an array in JavaScript
The easiest way to shuffle an array in JavaScript is to use the sort()
method.
The sort
method takes a callback function as a parameter.
This callback function takes the two elements to compare as parameter, and returns a number, which is used to determine the order of the elements.
If this number is negative, the first element will be before the second element, if it's positive, the second element will be before the first element, and if it's 0, the order of the elements will not change.
We can randomize an array by making the callback function randomly return a negative number, a positive number, or 0
.
The easiest way to do this is to use the Math.random()
function.
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = array.sort(() => Math.random() - 0.5);
Because each time the callback function is called, the result will be different, it will essentially randomize the array.
Just keep in mind that the sort()
method mutates the original array. So, if you want to keep the original array, make a copy first.
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = [...array].sort(() => Math.random() - 0.5);
Conclusion
In this post, we learned the easiest way to shuffle an array in JavaScript.
Simply use the sort()
method and pass in a callback function that returns a random number to determine the order.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications