The de-facto unbiased shuffle algorithm is the Fisher–Yates (aka Knuth) Shuffle.

You can see a great visualization here.

function shuffle(array) {
  let currentIndex = array.length;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
}

// Used like so
let arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › random
Math.random() - JavaScript - MDN Web Docs
This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. js · function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } This example returns a random integer between the specified values.
Top answer
1 of 16
2621

The de-facto unbiased shuffle algorithm is the Fisher–Yates (aka Knuth) Shuffle.

You can see a great visualization here.

function shuffle(array) {
  let currentIndex = array.length;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
}

// Used like so
let arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

2 of 16
1276

Here's a JavaScript implementation of the Durstenfeld shuffle, an optimized version of Fisher-Yates:

/* Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

It picks a random element for each original array element, and excludes it from the next draw, like picking randomly from a deck of cards.

This clever exclusion swaps the picked element with the current one, then picks the next random element from the remainder, looping backwards for optimal efficiency, ensuring the random pick is simplified (it can always start at 0).

Note the loop condition skips i==0, since j can only ever be 0 then, leading to no swap.

Algorithm runtime is O(n). Note that the shuffle is done in-place so if you don't want to modify the original array, first make a copy of it with .slice(0).


EDIT: Updating to ES6 / ECMAScript 2015

The new ES6 allows us to assign two variables at once. This is especially handy when we want to swap the values of two variables, as we can do it in one line of code. Here is a shorter form of the same function, using this feature.

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]];
    }
}
🌐
W3Schools
w3schools.com › js › js_random.asp
JavaScript Random
JS Examples JS HTML DOM JS HTML ... JS Interview Prep JS Bootcamp JS Certificate JS Reference ... Math.random() always returns a number lower than 1....
🌐
CodeHS
codehs.com › tutorial › 12907
Tutorial: Randomization in JavaScript | CodeHS
Click on one of our programs below to get started coding in the sandbox
🌐
Mimo
mimo.org › glossary › javascript › random
JavaScript Random: Syntax, Usage, and Examples
You can build random selection tools, quizzes, or random content generators using this pattern. JSX · Open in Mimo · Open in Mimo · Copy Code · const roll = Math.floor(Math.random() * 6) + 1; console.log("You rolled a", roll); This generates a number between 1 and 6, just like a physical die.
🌐
CoreUI
coreui.io › blog › how-to-generate-a-random-number-in-javascript
Javascript Random - How to Generate a Random Number in JavaScript? · CoreUI
April 16, 2024 - If you need the range to be inclusive of both ends [min, max], adjust the formula to: Math.floor(Math.random() * (max - min + 1)) + min. Follow Łukasz Holeczek on GitHub Connect with Łukasz Holeczek on LinkedIn Follow Łukasz Holeczek on X (Twitter) Łukasz Holeczek, Founder of CoreUI, is a seasoned Fullstack Developer and entrepreneur with over 25 years of experience. As the lead developer for all JavaScript, React.js, and Vue.js products at CoreUI, they specialize in creating open-source solutions that empower developers to build better and more accessible user interfaces.
🌐
W3Schools
w3schools.com › jsref › jsref_random.asp
JavaScript Math random() Method
Math.random() is an ECMAScript1 (JavaScript 1997) feature.
Find elsewhere
🌐
npm
npmjs.com › package › random-js
random-js - npm
A mathematically correct random number generator library for JavaScript.. Latest version: 2.1.0, last published: 7 years ago. Start using random-js in your project by running `npm i random-js`. There are 315 other projects in the npm registry ...
      » npm install random-js
    
Published   May 30, 2019
Version   2.1.0
Author   Cameron Kenneth Knight
🌐
p5.js
p5js.org › reference › p5 › random
random
Returns a random number or a random element from an array.
🌐
Medium
medium.com › @j.marchand.dev › best-way-to-do-random-in-javascript-55ff10241342
Best way to do random in JavaScript | by Jean-Marie Marchand | Medium
July 9, 2022 - Best way to do random in JavaScript As a developer you must have heard that in programming, random isn’t really random, and unfortunately it’s true. In JavaScript we know this syntax: function …
🌐
Keploy
keploy.io › home › community › how to generate random numbers in javascript
How to Generate Random Numbers in JavaScript | Keploy Blog
November 1, 2024 - Learn to generate random numbers, integers, Booleans in JavaScript for different scenarios, from basic to advanced techniques.
🌐
Medium
coureywong.medium.com › how-to-shuffle-an-array-of-items-in-javascript-39b9efe4b567
How to shuffle an array of items in JavaScript | by Courey Wong | Medium
January 15, 2024 - If you know javascript there is no function that shuffles the items in an array. There is a sort function as well as a random function but the created function simply isn’t the best solution for a truly authentic and original item random generator.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-random
JavaScript Random - GeeksforGeeks
July 11, 2025 - JS Tutorial · Web Tutorial · ... JavaScript Random refers to the Math.random() function, which generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive)....
🌐
freeCodeCamp
freecodecamp.org › news › how-to-shuffle-an-array-of-items-using-javascript-or-typescript
How to Shuffle an Array of Items Using JavaScript or TypeScript
June 5, 2023 - By subtracting 0.5 from the result of Math.random(), you introduce a random value between -0.5 and 0.5. This random value will cause the comparison function to return negative, positive, or zero values in a random manner for different pairs of elements.
🌐
Math.js
mathjs.org › docs › reference › functions › random.html
math.js
math.random() // generate a random number between 0 and 1 math.random(max) // generate a random number between 0 and max math.random(min, max) // generate a random number between min and max math.random(size) // generate a matrix with random numbers between 0 and 1 math.random(size, max) // ...
🌐
Testim
help.testim.io › docs › generate-random-data-with-js
Generate random data with JS
Learn how to assign random data (user name, password, email etc.) to text fields dynamically
🌐
GitHub
github.com › davidbau › seedrandom
GitHub - davidbau/seedrandom: seeded random number generator for Javascript · GitHub
Seeded random number generator for JavaScript. ... Can be used as a plain script, a Node.js module or an AMD module.
Starred by 2.1K users
Forked by 169 users
Languages   JavaScript 81.3% | HTML 18.5% | Shell 0.2%