Shuffle an Array, array, js

Shuffle an Array in JavaScript

If you are working with arrays in JavaScript, you may sometimes want to shuffle their elements randomly. There are several ways to do this, and in this post, I will explain some of them.

Method 1: Using a For Loop and Math.random()

The first method involves using a for loop to iterate through the array and swapping each element with a randomly selected element. Here's how it works:


function shuffleArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    const j = Math.floor(Math.random() * arr.length);
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

const myArray = [1, 2, 3, 4, 5];
console.log(shuffleArray(myArray));

In this code, we define a function called shuffleArray() that takes an array as its argument. Inside the function, we use a for loop to iterate through the array, and for each iteration, we generate a random index between 0 and the length of the array using Math.floor(Math.random() * arr.length). We then swap the current element with the randomly selected element using destructuring assignment.

Method 2: Using the Fisher-Yates Shuffle Algorithm

The second method is the Fisher-Yates shuffle algorithm, which is a more efficient way to shuffle an array. Here's how it works:


function shuffleArray(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

const myArray = [1, 2, 3, 4, 5];
console.log(shuffleArray(myArray));

In this code, we define the same shuffleArray() function as in the first method, but we use a different algorithm to shuffle the elements. Instead of swapping each element with a randomly selected element, we start from the end of the array and swap each element with a random element before it. This ensures that each element has an equal chance of being in any position in the shuffled array.

Method 3: Using the Array.sort() Method

The third method is to use the Array.sort() method with a custom compare function that returns a random number. Here's how it works:


function shuffleArray(arr) {
  return arr.sort(() => Math.random() - 0.5);
}

const myArray = [1, 2, 3, 4, 5];
console.log(shuffleArray(myArray));

In this code, we define the shuffleArray() function that takes an array as its argument and returns a shuffled array using the Array.sort() method. The compare function used by Array.sort() returns a random number between -0.5 and 0.5, which ensures that the elements are shuffled randomly.

These are some of the ways to shuffle an array in JavaScript. Choose the one that suits your needs and use it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe