Solution
We're about to shuffle things up a bit and understand the magic behind a simple shuffling algorithm. Let's break down the given solution into smaller parts to understand how it all comes together.
Understanding the Shuffling Problem
The problem at hand is to write a function that takes an array and shuffles its elements in a random order.
Shuffling is a common task that we encounter in various applications, such as card games or creating randomized playlists. The idea is to rearrange the elements in a collection in a random order. But how do we ensure that every possible arrangement is equally likely? This is where the swapping technique comes into play.
Before we dive into the code, let's think about what we need to do. We need to visit each element in the array and exchange it with another randomly chosen element. This swapping ensures that every element has an equal chance to be in any position.
Step-by-Step Breakdown

Step 1: Setting up the Shuffle Function
We'll begin by defining our shuffle function, which takes an array as an input.
1function shuffle(arr) {
2 // The shuffling happens here!
3}
Step 2: Looping Through the Array
We need to loop through the array elements to shuffle them. A basic for
loop will do the job.
1for (let i = 0; i < arr.length; i++) {
2 // Shuffling each element
3}
Step 3: Generating a Random Index
A fair shuffle means that every element has an equal chance of landing in any position in the array. If we pick elements randomly and place them into a new array, we might unintentionally favor some elements over others.
For each element, we want to swap it with another randomly chosen element in the array. We'll generate a random index, j
, that is larger than the current index i
.
1const j = i + Math.floor(Math.random() * (arr.length - i));
Math.random()
gives a random value between 0 and 1.- We multiply this by
(arr.length - i)
to make sure the index is larger thani
. - We add
i
to ensure that the value is always greater than the current index. Math.floor()
rounds the value to an integer.
Step 4: Swapping the Elements
Now that we have our random index, we'll swap the elements at indices i
and j
. We'll use the array destructuring syntax to make this concise.
1[arr[i], arr[j]] = [arr[j], arr[i]];