3 Ways to Shuffle an Array in JavaScript

Shuffling an array is a common operation in programming, especially when dealing with randomized tasks or creating varied user experiences.

Shuffling arrays is a fundamental task in JavaScript programming.

Whether you’re creating games, randomizing content, or building dynamic user interfaces, knowing how to shuffle arrays is a valuable skill.

In JavaScript, shuffling an array involves rearranging its elements randomly.

In this article, we’ll explore various techniques to shuffle an array effectively, along with code examples and explanations.

Array shuffling involves changing the order of elements in an array randomly.

This is often required in applications such as card games, randomized lists, and random animations. JavaScript offers several approaches to achieve this, each with its own advantages and trade-offs.

Method #1 Using the Sort Function

Surprisingly, you can use the built-in sort function to shuffle an array.

This is based on the fact that the sort function is not guaranteed to be stable, meaning that it might not maintain the original order of equal elements.

function sortShuffle(array) {
  return array.sort(() => Math.random() - 0.5);
}

Method #2 Using the Fisher-Yates Algorithm

The Fisher-Yates shuffle, also known as the Knuth shuffle, is a widely used algorithm for shuffling arrays.

It has an O(n) time complexity, making it efficient for shuffling even large arrays.

Here’s the basic idea behind the algorithm:

  1. Start from the last element of the array.
  2. Swap the current element with a randomly selected element that comes before it (including itself).
  3. Move one step backwards in the array and repeat the process until you reach the first element.
function fisherYatesShuffle(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]];
   }
}

Method #3 Shuffling with the Knuth Shuffle Algorithm

The Knuth Shuffle is a variation of the Fisher-Yates shuffle that shuffles an array in place.

See also  Puppeteer Tutorial #3 - Extract SEO Insights and Data Analysis

It ensures that each element is equally likely to end up in any position.

function knuthShuffle(array) {
  let currentIndex = array.length, randomIndex, tempValue;

  while (currentIndex !== 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
  }
}

In this article, we explored various techniques including the Fisher-Yates Algorithm, the Sort Function, and the Knuth Shuffle Algorithm.

Each technique has its own advantages, so you can choose the one that best fits your specific use case. Happy shuffling!