Skip to main content

Array

๐Ÿš€ Frontend DSA 4 - ๐Ÿ”€ How to Shuffle an Array Randomly in JavaScript (Fisher-Yates Explained)

Ever wanted to shuffle an array like a deck of cards? ๐ŸŽด Whether you're building a quiz app, a game, or need random ordering, shuffling arrays is a must-have trick in your JavaScript toolbox. ๐Ÿš€

Letโ€™s break down a clean and beginner-friendly way to shuffle any array using JavaScript.


๐Ÿ“š What Youโ€™ll Learn

  • How to shuffle an array randomly in JavaScript ๐Ÿ’ก
  • Why the Fisher-Yates Shuffle Algorithm is ideal ๐ŸŽฒ
  • Mistakes to avoid when shuffling โŒ
  • Sample inputs and outputs to test your learning ๐Ÿงช

๐Ÿšซ Common Mistake (โŒ Original Example)

Before diving into the correct way, hereโ€™s a version with a subtle bug ๐Ÿ‘‡

const shuffleArray = (inputArray = []) => {
  for (let i = 0; i < inputArray.length; i++) {
    let randomIndex = Math.floor(Math.random() * 5); // โŒ Hardcoded limit = 5

    // Swap logic
    let temp = inputArray[randomIndex];
    inputArray[randomIndex] = inputArray[i];
    inputArray[i] = temp;
  }
};

Problem Statement

โŒ Why is this incorrect?

  • Math.random() * 5 is hardcoded and will not work for arrays larger or smaller than 5.
  • It might cause undefined access or missed elements.

โœ… Correct Solution: Fisher-Yates Shuffle ๐Ÿง 

Hereโ€™s the correct and optimal implementation:

// โœ… Fisher-Yates Shuffle Algorithm
const shuffleArray = (inputArray = []) => {
  for (let i = inputArray.length - 1; i > 0; i--) {
    // Pick a random index from 0 to i
    const randomIndex = Math.floor(Math.random() * (i + 1));

    // Swap elements at i and randomIndex
    const temp = inputArray[i];
    inputArray[i] = inputArray[randomIndex];
    inputArray[randomIndex] = temp;
  }
  return inputArray; // Optional: return shuffled array
};

Problem Statement


๐Ÿ”ข Sample Inputs and Outputs

๐Ÿงช Example 1:

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

๐ŸŽฒ Possible Output:

[3, 5, 1, 2, 4]

๐Ÿงช Example 2:

let arr2 = ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐Ÿ“", "๐Ÿ"];
console.log(shuffleArray(arr2));

๐ŸŽฒ Possible Output:

["๐Ÿ‡", "๐Ÿ", "๐ŸŒ", "๐ŸŽ", "๐Ÿ“"]

๐Ÿงช Example 3:

let arr3 = [true, false, true, false];
console.log(shuffleArray(arr3));

๐ŸŽฒ Possible Output:

[false, true, false, true]

๐Ÿง  JavaScript Notes

  • Math.random() generates a floating number from 0 (inclusive) to 1 (exclusive).
  • Math.floor(Math.random() * (i + 1)) gives a safe index from 0 to i.
  • The Fisher-Yates algorithm guarantees a uniform distribution โ€” each permutation is equally likely!

๐Ÿงฉ When Should You Shuffle an Array?

  • ๐ŸŽฎ In games (e.g., random card draw)
  • ๐Ÿงช In testing (e.g., randomizing test cases)
  • ๐Ÿ“Š In data visualization (e.g., shuffling chart entries)
  • ๐Ÿง  In interviews (you might be asked to implement this!)

โš ๏ธ Bonus Tip: Never Use .sort(() => Math.random() - 0.5)

Although it seems to work:

array.sort(() => Math.random() - 0.5);

It is not reliable or uniformly random across all engines. โŒ Use Fisher-Yates instead for best results.


๐ŸŽ‰ Final Thoughts

Shuffling an array is one of those things that seems easy โ€” until you dive into the details! Now you know how to do it correctly, and even explain it in your next interview. ๐Ÿ’ฌ

Want a visual animation of how the algorithm swaps elements step by step? Let me know! ๐Ÿง‘โ€๐Ÿ’ป


Hey there from LearnYard! ๐Ÿ‘‹

Glad to see you exploring the free content from our course! Weโ€™ve shared 10 valuable articles at no cost to help you get a real feel of whatโ€™s inside.

If youโ€™ve found these helpful, weโ€™d love to know! ๐Ÿ’ฌ
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram โ€” and donโ€™t forget to tag Gourav Hammad & Mohammad Fraz. Weโ€™ll personally respond to your post!

Thanks for being part of the LearnYard journey. Keep learning, keep growing! ๐Ÿš€


Loved the free content? Want access to the full course โ€” for free? ๐Ÿ’ธ

Share the course with your friends using your affiliate link (youโ€™ll find it on your profile or home page), and earn 20% commission on each sale.

Just 4โ€“5 sales and youโ€™ll recover the full course price of your course ๐Ÿ”
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! ๐Ÿ› ๏ธ๐Ÿ“ˆ


๐Ÿ“š Keywords for SEO

  • Shuffle Array in JavaScript
  • JavaScript Randomize Array Order
  • Fisher-Yates Shuffle Algorithm Explained
  • How to Randomize Elements in JavaScript
  • JavaScript Shuffle Array Without Using sort()
  • Efficient Array Shuffling in JS
  • Random Shuffle Utility Function in JavaScript
  • Implementing Fisher-Yates Shuffle in JavaScript
  • Shuffling Arrays Without Bias in JS
  • Beginner-Friendly Shuffle Logic in JavaScript

๐Ÿ“ข Hashtags for Visibility

#JavaScriptTips #ShuffleArray #FisherYatesAlgorithm #FrontendInterviewPrep
#JSWithoutSort #RandomizeArrayJS #WebDevelopment #LearnJavaScript
#CodeNewbie #JavaScriptDeepDive #JSForBeginners #VanillaJavaScript
#FrontendMasters #JSInterviewPrep #CodingChallenges #TechLearning
#JavaScriptAlgorithms #ShuffleLogic #EfficientJS #FrontendDevelopment