How to Shuffle the Items in an Array in JavaScript

Shuffle the Items in an Array in JavaScript

Shuffling an array means randomly rearranging its items. This is useful in many situations—from randomizing a quiz or shuffling a deck of cards, to showing featured products in a different order each time. In JavaScript, while there’s no built-in method like shuffle(), it’s easy to implement with the right approach.

This tutorial will guide you through several beginner-friendly methods to shuffle an array, with simple examples like ["apple", "banana", "cherry", "date"].

Method 1: Fisher-Yates Shuffle (Recommended)

The Fisher-Yates algorithm is the gold standard for shuffling. It works by iterating from the end of the array to the beginning, swapping each item with a random earlier one. This method ensures a fair and uniform distribution.

function shuffleArray(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]];
  }
  return array;
}

const fruits = ["apple", "banana", "cherry", "date"];
console.log(shuffleArray(fruits));
["cherry", "apple", "banana", "date"] // output will vary each time

Method 2: Using sort() with Math.random() (Not Fully Reliable)

This trick uses the sort() method with a random comparator to mix items. It’s short and looks elegant, but the results are not guaranteed to be uniformly random, especially for large datasets.

const fruits = ["apple", "banana", "cherry", "date"];
const shuffled = fruits.sort(() => Math.random() - 0.5);
console.log(shuffled);
["banana", "date", "apple", "cherry"] // output may vary

Method 3: Creating a Reusable Shuffle Function

When you want to keep your logic clean and modular, it’s a good idea to wrap your shuffle logic in a function. You can use the Fisher-Yates approach here and make your code portable across projects.

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

const fruits = ["apple", "banana", "cherry", "date"];
console.log(getShuffled(fruits));
["date", "cherry", "banana", "apple"] // different every time

Bonus Tip: Shuffle Without Mutating the Original Array

JavaScript’s array methods often mutate the original array. If you want to keep the original untouched, use slice() or the spread operator to make a shallow copy before shuffling:

const original = ["apple", "banana", "cherry"];
const shuffled = shuffleArray([...original]);
console.log("Original:", original);
console.log("Shuffled:", shuffled);
Original: ["apple", "banana", "cherry"]
Shuffled: ["cherry", "apple", "banana"]

Which Method Should You Use?

  • Use Fisher-Yates for accurate, unbiased shuffling—especially in games, testing, or critical logic.
  • ⚠️ Use sort(() => Math.random() - 0.5) for quick demos or simple UI shuffles.
  • Use reusable functions when you want clean, testable, and scalable logic.

Final Thoughts

Shuffling arrays in JavaScript might look like a party trick, but it's a practical skill used in everything from random quizzes to card games and playlist generation. The Fisher-Yates algorithm gives you fairness and reliability, while the quick sort() trick gives you speed and simplicity—if you’re okay with slightly unpredictable results.

Pick the method that fits your use case. And if you're building for real users or need fairness, always reach for Fisher-Yates. It’s the algorithm that’s been tested, trusted, and time-approved for decades.

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...