Shuffle an Array in JavaScript

The most common way to shuffle an array in JavaScript is by using the Fisher-Yates shuffle algorithm.

This algorithm efficiently shuffles an array in place. Here’s a straightforward way to implement this algorithm in JavaScript (I'll share an explanation after the code).

Also, while looking for the algorithm, I found this. It's a great visualization/explanation of the algorithm in action.

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    // Generate a random index lower than the current element index
    const j = Math.floor(Math.random() * (i + 1));

    // Swap elements i and j
    [array[i], array[j]] = [array[j], array[i]];
  return array;

// Usage
const myArray = [1, 2, 3, 4, 5];
console.log(myArray); // Outputs random order like: [3, 5, 4, 1, 2]

How It Works

  1. We loop over the array from the end of the array and decrement down to the second element.
  2. Randomly select an index from 0 to the current index i.
  3. Swap the element at the current index i with the element at the randomly selected index j.

When you run the function with an example array, it randomly shuffles the elements each time you execute it.

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.