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);

🌐
CodeHS
codehs.com › tutorial › 12907
Tutorial: Randomization in JavaScript | CodeHS
JavaScript Tutorial · javascript · By Ryan Hart · High School · javascript · By Rachel Devaney · High School · Coding LMS · Online IDE · CodeHS Pro · Computer Science Curriculum · Certifications · Professional Development · AI Creator · Typing · Cyber Range ·
🌐
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 - Now we just have to replace Math.random() by our safe float with the same method presented at the beginning.
🌐
W3Schools
w3schools.com › jsref › jsref_random.asp
JavaScript Math random() Method
The Math.random() method returns a random floating point number between 0 (inclusive) and 1 (exclusive).
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]];
    }
}
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Math › random
JavaScript Math random() - Generate Random Number | Vultr Docs
November 29, 2024 - The Math.random() method in JavaScript is an essential tool for generating random numbers. This function returns a floating-point, pseudo-random number in the range from 0 (inclusive) to 1 (exclusive), which you can then scale to your desired range.
🌐
p5.js
p5js.org › reference › p5 › random
random
The randomSeed() function can be used to generate the same sequence of numbers or choices each time a sketch runs.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › random
Math.random() - JavaScript - MDN Web Docs
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random ...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Generate Random Whole Numbers with JavaScript - JavaScript - The freeCodeCamp Forum
April 18, 2023 - Tell us what’s happening: The instructions for this lesson ask you to use the Math.floor(Math.random()) * N to generate and return a random whole number between 0 and 9 When I return Math.floor(Math.random()*9) it is…
Find elsewhere
🌐
Mimo
mimo.org › glossary › javascript › random
JavaScript Random: Syntax, Usage, and Examples
Math.random() returns a pseudo-random number between 0 (inclusive) and 1 (exclusive)—great for games, picks, timers, colors, or password generators.
🌐
W3Schools
w3schools.com › js › js_random.asp
JavaScript Random
As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes. This JavaScript function always returns a random integer between min (included) and max (excluded):
🌐
W3docs
w3docs.com › javascript
How to Randomize (shuffle) a JavaScript Array
In JavaScript, there no any built-in method of shuffling a JavaScript array. Read this tutorial and learn what is the popular method of randomizing arrays.
🌐
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 - JavaScript offers various ways ... in your output. In this article, we aim to introduce beginners to the simplest methods of generating random numbers in JavaScript using the Math.random() function....
🌐
Math.js
mathjs.org › docs › reference › functions › random.html
math.js | an extensive math library for JavaScript and Node.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) // ...
🌐
Hyperskill
hyperskill.org › university › javascript › javascript-random
JavaScript Random
August 2, 2024 - ‍ For generating decimal numbers within a specified range multiply the result of Math.random() by the desired range and add the minimum value. For example to get a decimal number between 5.5 and 10.5; ... JavaScript is a programming language that enables dynamic website development.
🌐
Smashing Magazine
smashingmagazine.com › 2024 › 08 › generating-unique-random-numbers-javascript-using-sets
Generating Unique Random Numbers In JavaScript Using Sets — Smashing Magazine
August 26, 2024 - Want to create more randomized effects in your JavaScript code? The `Math.random()` method alone, with its limitations, won’t cut it for generating unique random numbers. Amejimaobari Ollornwi explains how to generate a series of unique random numbers using the `Set` object, how to use these ...
🌐
Udacity
udacity.com › blog › 2021 › 04 › javascript-random-numbers.html
Creating Javascript Random Numbers with Math.random() | Udacity
September 27, 2022 - Javascript is a full programming language, able to make complex mathematical calculations. Learn how you can create random numbers with Math.random()
🌐
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 - In coding terms I basically wanted to shuffle the items in my array randomly. If you know javascript there is no function that shuffles the items in an array.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-random-number-how-to-generate-a-random-number-in-js
JavaScript Random Number – How to Generate a Random Number in JS
August 3, 2022 - In this article, you will learn how to use the Math.random() method to retrieve random numbers. ... JavaScript has the Math built-in static object, which allows you to perform mathematical calculations and operations.
🌐
Career Karma
careerkarma.com › blog › javascript › javascript random number: a complete guide
JavaScript Random Number: A Complete Guide
December 1, 2023 - The Math.random() JavaScript function can be used to generate random numbers between 0 (inclusive) and 1 (exclusive).