By Click Upvote

2010-03-15 22:37:11 8 Comments

I have an array like this:

var arr1 = ["a", "b", "c", "d"];

How can I randomize / shuffle it?


@Erik Martín Jordán 2020-07-03 10:05:04

Using Fisher-Yates shuffle algorithm and ES6:

// Original array
let array = ['a', 'b', 'c', 'd'];

// Create a copy of the original array to be randomized
let shuffle = [...array];

// Defining function returning random value from i to N
const getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i);

// Shuffle a pair of two elements at random position j
shuffle.forEach( (elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]] );

// ['d', 'a', 'b', 'c']

@Ben Carp 2017-09-11 18:12:18

Shuffle Array In place

    function shuffleArr (array){
        for (var i = array.length - 1; i > 0; i--) {
            var rand = Math.floor(Math.random() * (i + 1));
            [array[i], array[rand]] = [array[rand], array[i]]

ES6 Pure, Iterative

    const getShuffledArr = arr => {
        const newArr = arr.slice()
        for (let i = newArr.length - 1; i > 0; i--) {
            const rand = Math.floor(Math.random() * (i + 1));
            [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
        return newArr

Reliability and Performance Test

Some solutions on this page aren't reliable (they only partially randomise the array). Other solutions are significantly less efficient. With testShuffleArrayFun (see below) we can test array shuffling functions for reliability and performance.

    function testShuffleArrayFun(getShuffledArrayFun){
        const arr = [0,1,2,3,4,5,6,7,8,9]

        var countArr =>{
                el=> 0
        }) //   For each possible position in the shuffledArr and for 
           //   each possible value, we'll create a counter. 
        const t0 =
        const n = 1000000
        for (var i=0 ; i<n ; i++){
            //   We'll call getShuffledArrayFun n times. 
            //   And for each iteration, we'll increment the counter. 
            var shuffledArr = getShuffledArrayFun(arr)
        const t1 =
        console.log(`Count Values in position`)

        const frequencyArr = positionArr => (
                count => count/n

        console.log("Frequency of value in position")
        console.log(`total time: ${t1-t0}`)

Other Solutions

Other solutions just for fun.

ES6 Pure, Recursive

    const getShuffledArr = arr => {
        if (arr.length === 1) {return arr};
        const rand = Math.floor(Math.random() * arr.length);
        return [arr[rand], ...getShuffledArr(arr.filter((_, i) => i != rand))];

ES6 Pure using

    function getShuffledArr (arr){
        return [...arr].map( (_, i, arrCopy) => {
            var rand = i + ( Math.floor( Math.random() * (arrCopy.length - i) ) );
            [arrCopy[rand], arrCopy[i]] = [arrCopy[i], arrCopy[rand]]
            return arrCopy[i]

ES6 Pure using array.reduce

    function getShuffledArr (arr){
        return arr.reduce( 
            (newArr, _, i) => {
                var rand = i + ( Math.floor( Math.random() * (newArr.length - i) ) );
                [newArr[rand], newArr[i]] = [newArr[i], newArr[rand]]
                return newArr
            }, [...arr]

@sheriffderek 2017-09-11 19:00:09

So, where is the ES6(ES2015) ? [array[i], array[rand]]=[array[rand], array[i]] ? Maybe you can outline how that works. Why do you choose to iterate downwards?

@Ben Carp 2017-09-12 02:47:33

@sheriffderek Yes, the ES6 feature I'm using is the assignment of two vars at once, which allows us to swap two vars in one line of code.

@Ben Carp 2017-09-15 01:00:10

Credit to @sheriffderek who suggested the ascending Algorithm. The ascending algorithm could be proved in induction.

@Aljohn Yamaro 2020-04-21 04:14:51

Here is the EASIEST one,

function shuffle(array) {
  return array.sort(() => Math.random() - 0.5);

for further example, you can check it here

@Stiakov 2020-04-02 23:24:25

Shuffling array using recursion JS.

Not the best implementation but it's recursive and respect immutability.

const randomizer = (array, output = []) => {
    const arrayCopy = [...array];
    if (arrayCopy.length > 0) {    
        const idx = Math.floor(Math.random() * arrayCopy.length);
        const select = arrayCopy.splice(idx, 1);
        randomizer(arrayCopy, output);
    return output;

@superluminary 2017-10-03 13:16:52

You can do it easily with map and sort:

let unshuffled = ['hello', 'a', 't', 'q', 1, 2, 3, {cats: true}]

let shuffled = unshuffled
  .map((a) => ({sort: Math.random(), value: a}))
  .sort((a, b) => a.sort - b.sort)
  .map((a) => a.value)
  1. We put each element in the array in an object, and give it a random sort key
  2. We sort using the random key
  3. We unmap to get the original objects

You can shuffle polymorphic arrays, and the sort is as random as Math.random, which is good enough for most purposes.

Since the elements are sorted against consistent keys that are not regenerated each iteration, and each comparison pulls from the same distribution, any non-randomness in the distribution of Math.random is canceled out.


Time complexity is O(N log N), same as quick sort. Space complexity is O(N). This is not as efficient as a Fischer Yates shuffle but, in my opinion, the code is significantly shorter and more functional. If you have a large array you should certainly use Fischer Yates. If you have a small array with a few hundred items, you might do this.

@Bergi 2017-12-06 19:42:40

@superluminary Oops, you're right. Notice that this answer already used the same approach.

@superluminary 2017-12-07 11:24:08

@Bergi - Ah yes, you are right, although I think my implementation is slightly prettier.

@Mark Grimes 2018-06-29 10:43:18

Very nice. This is the Schwartzian transform in js.

@superluminary 2018-07-09 12:28:36

@torazaburo - It's not as performant as Fischer Yates, but it's prettier and the code is smaller. Code is always a trade-off. If I had a large array, I would use Knuth. If I had a couple of hundred items, I would do this.

@HynekS 2018-10-26 17:51:10

I like the simplicity of this code, but it is incomparably slower than Fischer-Yates – see this JSPerf test. I would also suggest using Symbol, e.g. [Symbol.sort] to prevent collision with a property name.

@superluminary 2018-11-05 11:45:59

@HynekS - It's not fast code I agree, but it's simple. The difference should only be noticeable on quite large arrays. The objects inherit directly from Object, so there should be no collision with the sort attribute. I don't think Symbols are necessary here?

@HynekS 2018-11-05 12:13:14

@superluminary: You are absolutely right about Symbols, I was thinking about the edge of sorting an array including {sort: 'something'} objects, but I did a test and it works perfectly, no need for Symbols. I believe that if your array is 'short', you can afford the performance cost, but I did a test on arrays of 1000 elements – and the test speaks fot itself, see the link to JSPerf.

@Ben Carp 2019-11-09 10:45:27

This is an elegant solution to the issue/problem present in However, according to my tests it is significantly less efficient than the standard/iterative/swapping places solution, probably because it's using array.sort

@superluminary 2019-11-11 10:42:42

@BenCarp - Agreed,It is not the fastest solution and you would not want to use it on a massive array, but there are more considerations in code than raw speed.

@deadrunk 2013-09-06 04:55:22

The use of this algorithm is not recommended, because it is inefficient and strongly biased; see comments. It is being left here for future reference, because the idea is not that rare.

[1,2,3,4,5,6].sort(function() {
  return .5 - Math.random();

@Alex K 2013-10-28 09:49:32

i like this solution, enough to give a basic random

@radtad 2013-11-13 18:35:08

Downvoting as this isn't really that random. I don't know why it has so many upvotes. Do not use this method. It looks pretty, but isn't completely correct. Here are results after 10,000 iterations on how many times each number in your array hits index [0] (I can give the other results too): 1 = 29.19%, 2 = 29.53%, 3 = 20.06%, 4 = 11.91%, 5 = 5.99%, 6 = 3.32%

@deadrunk 2013-11-21 00:37:30

It's fine if you need to randomize relatively small array and not dealing with cryptographic things. I totally agree that if you need more randomness you need to use more complex solution.

@Blazemonger 2013-12-17 14:21:01

@Ivan Yan 2014-05-13 08:42:58

@radtad I did a test, the result is 16%~17%

@MatsLindh 2014-09-10 14:07:44

The problem is that it's not deterministic, which will give wrong results (if 1 > 2 and 2 > 3, it should be given that 1 > 3, but this will not guarantee that. This will confuse the sort, and give the result commented by @radtad).

@Ultimater 2014-10-29 23:17:37

sort() for randomizing an array has a strong bias toward keeping each element in its initial starting position in addition to the edges of the array having slightly more bias than the middle:

@Andre Figueiredo 2014-11-16 18:32:37

Would it be random enough if I put it in a loop to run x times? When x is the size of array?

@Bergi 2015-04-03 20:48:46

@Luca C. 2016-07-29 07:29:08

ok, any efficent and correct method that is writable in 1/3 lines?

@Master James 2017-03-22 12:18:54

It's pretty good. [1,2,3,4,5,6].sort(function() { return (.5 - Math.random() > .5 - Math.random()); }); If you also randomly reverse it.

@Master James 2017-03-22 12:25:13

var ans = [1,2,3,4,5,6,8,9,10,11,12,13,14,15,16].sort(function() { return (.5 - Math.random() > 0); }); if(.5 - Math.random() > 0) ans.reverse(); else ans;

@Master James 2017-03-22 12:32:41

No it doesn't really work with more then a handful, depends on randomizer partly too.

@Nisim Joseph 2017-12-06 14:09:09

why did you do (0.5 - random) ? it the same order and not doing any meaningful action. just want to understand that.

@Ally 2018-03-18 00:58:54

It's true, wrote some code to test it

@JayJay123 2020-02-25 03:04:52

As a one liner providing some randomness to the sorting of the few answers in a multiple choice quiz, it works just fine.

@Dan 2020-03-22 12:38:25

The 10,000 iteration percentages are wildly inaccurate and not nearly as bad as claimed. See for yourself. This method is still skewed though. @radtad

@Laurens Holst 2012-09-28 20:20:11

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), and thereby skipping the final element.

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

@Laurens Holst 2012-09-28 20:47:51

p.s. The same algorithm as ChristopheD’s answer, but with explanation and cleaner implementation.

@Pacerier 2014-10-31 12:32:11

People are attributing the wrong person for the algorithm. It's not Fisher-Yates shuffle but Durstenfeld shuffle. The true original Fisher-Yates algorithm is runs in n^2 time, not n time

@Hengameh 2015-09-22 00:31:49

Could you please tell me which one you think is better for shuffling? (Link: As i tested, there is no difference between them.

@Joel Trauger 2016-08-09 13:31:21

It is not required to return array since JavaScript passes arrays by reference when used as function arguments. I assume this is to save on stack space, but it's an interesting little feature. Performing the shuffle on the array will shuffle the original array.

@Marjan Venema 2016-12-18 20:17:49

The implementation in this answer favors the lower end of the array. Found out the hard way. Math.random() should not be multiplied with the loop counter + 1, but with array.lengt()`. See Generating random whole numbers in JavaScript in a specific range? for a very comprehensive explanation.

@user94559 2017-03-11 01:44:06

@MarjanVenema Not sure if you're still watching this space, but this answer is correct, and the change you're suggesting actually introduces bias. See for a nice writeup of this mistake.

@Marjan Venema 2017-03-11 14:54:08

Not very active anymore but I do keep track of notifications, @smarx. Thanks for that. Interesting read. What I don't understand is why I saw a definite bias towards the lower end using the code above? See After using the solution from the answer I linked in my comment, distribution seemed much more even.

@user94559 2017-03-11 17:39:35

@MarjanVenema I have no explanation for that. Perhaps there was some other bug in your code. What was your sample size when you looked at the results? Perhaps the pattern you noticed at first was just dumb luck.

@Marjan Venema 2017-03-12 12:23:11

Code was a straight copy of this post ;) I guess it was indeed just dumb luck, but as the task attached to the outcome was considered a "chore" rather than something nice, complaints ran rampant... You know developers: there must be something wrong with your code.

@roottraveller 2017-07-27 14:18:33

@LaurensHolst why we are running from last index to first index i.e n-1 to 0? Is there any particular advantage that I'm unable to see here ??

@Laurens Holst 2017-07-31 21:39:08

@roottraveller It simplifies the code. If it ran forwards the random range would need to be calculated (len - i), and the resulting random index would need to be offset by the current position (+ i). I allude to this in the description, but maybe this makes it more clear. Try to rewrite it yourself, and see!

@bryc 2017-11-25 09:47:02

for (let i = array.length - 1; i > 0; i--) should be for (let i = array.length - 1; i >= 0; i--). It appears to be missing the first array index.

@Laurens Holst 2017-12-11 19:00:36

@bryc As mentioned in the description, “it skips the last element because there are no other choices anymore.” Math.floor(Math.random() * (0 + 1)) will always return 0, and would thus only swap with itself, so there’s no point in doing the last swap.

@Martin Burch 2018-05-08 13:10:11

Does this need a return array; at the end?

@nnyby 2018-12-07 19:41:48

@MartinBurch here's a version that doesn't modify the original array and returns a new one.

@x-yuri 2019-02-28 15:54:06

@Pacerier So it's Durstenfeld shuffle algorithm that is given in the other answer. Not Fisher-Yates?

@EssenceBlue 2019-11-07 16:26:42

Works also by including last element like this: for (var i = array.length - 1; i >= 0; i--) {...}

@ChristopheD 2010-03-15 22:41:10

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


You can see a great visualization here (and the original post linked to this)

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

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

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

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

  return array;

// Used like so
var arr = [2, 11, 37, 42];

Some more info about the algorithm used.

@nikola 2010-03-16 08:02:36

... except that Math.random() is not random at all, and therefore the Fisher-Yates Shuffle will not randomly shuffle for sufficiently large sets. Just pointing this out in case someone attempts to the latter.

@Click Upvote 2010-03-17 00:09:56

@prometheus , what do you mean math.random is not random? why is it called math.random if it isnt?

@Derek Dahmer 2011-03-08 01:57:54

Here's a CoffeeScript implementation of the Fisher-Yates algorithm:

@RobG 2011-06-08 07:21:31

The above answer skips element 0, the condition should be i-- not --i. Also, the test if (i==0)... is superfluous since if i == 0 the while loop will never be entered. The call to Math.floor can be done faster using ...| 0. Either tempi or tempj can be removed and the value be directly assigned to myArray[i] or j as appropriate.

@Phil H 2012-04-13 14:10:09

@prometheus, all RNGs are pseudo-random unless connected to expensive hardware.

@jm. 2012-04-18 21:29:23

Is @RobG right? Why don't you post another answer, RobG, instead of commenting this one.

@RobG 2012-04-19 00:58:02

@jm—About skipping zero? In the test while (--i) then if i = 1 when the loop starts, it will first be decremented to zero before being tested. The test will return false and so the loop isn't executed when i == 0. As for returning false if length is zero, that makes no sense at all - shuffling an empty array should just return the empty array. Another answer? There a zillion articles on the web about shuffling.

@RobG 2012-04-19 01:57:43

Oh, a good resource for shuffl, deal and draw is

@theon 2012-07-20 12:57:47

@RobG the implementation above is functionally correct. In the Fisher-Yates algorithm, the loop isn't meant to run for the first element in the array. Check out wikipedia where there are other implementations that also skip the first element. Also check out this article which talks about why it is important for the loop not to run for the first element.

@joeytwiddle 2012-10-08 14:55:27

@RobG, @jm, Math.random() returns a number 0<=n<1. So after flooring Math.random() * ( 0 + 1 ) you'll always be swapping the first element with itself.

@RobG 2012-10-09 00:27:39

@joeytwiddle—|0 is just a different way to floor the value, happy with theon's explanation of why the first item should be skipped.

@frabcus 2013-04-04 15:07:58

Bad to give a particular implementation - should use one from a library.

@toon81 2013-04-24 09:19:48

@nikola "not random at all" is a little strong a qualification for me. I would argue that it is sufficiently random unless you're a cryptographer, in which case you're probably not using Math.Random() in the first place.

@theGrayFox 2014-06-14 21:07:03

Another good read for ensuring your algorithm is on point.

@scaryguy 2015-11-22 11:30:49

Anyone who is going to use this implementation: DO NOT forget that this will CHANGE the given array! This will NOT create a new one and return a new array!..

@Mohammed Zameer 2016-01-26 15:59:15

@theon This returns duplicate results? Is my understanding wrong?

@theon 2016-01-29 10:29:21

@student It is a random shuffle. For an array with 4 elements, there are only 24 permutations. So for a given shuffle, another shuffle has a 1 in 24 chance of being the same. After 25 shuffles you are guaranteed to have at least one pair of duplicate results.

@Christos Hayward 2016-07-16 15:43:49

@nikola Remember, the importance of random number generation is too important to leave to chance.

@Jürgen Paul 2016-07-21 08:13:12

Does anyone know the inside-out version of this?…

@user993683 2017-01-20 01:11:54

Why arr = shuffle(arr); and not just shuffle(arr);? The array is passed in by reference so you can just keep the original reference.

@ffxsam 2017-02-12 07:18:52

Ugh, yoda (0 !== currentIndex).

@gman 2017-04-06 23:28:02

This would be faster with Math.random() * currentIndex | 0

@sonlexqt 2017-06-27 17:43:08

If you don't want to modify the old array, add var clone = array.slice(0); on the first line and then return the clone array instead.

@Alexander Mills 2018-07-13 03:51:26

An immutable version of this which does not manipulate the input would be good.

@Matt Ellis 2018-12-13 23:33:05

The visualization is a great addition to this answer; Mike Bostock is awesome!

@Lax_Sam 2018-12-24 06:17:48

var currentIndex = array.length, temporaryValue, randomIndex; Can anyone explain what is happening in this line? I am new to javascript and could not understand how this assignment works.

@Lee Blake 2019-02-03 15:38:58

I'm using this function and it works to randomize the array, but when I run it twice on the same original array, I get the same output both times.

@BallpointBen 2020-04-09 20:58:53

The key phrase from that visualization that made Fisher-Yates click for me: "We use the back of the array to store the shuffled elements, and the front of the array to store the remaining elements. We don’t care about the order of the remaining elements as long as we sample uniformly when picking!"

@Frangiskos 2020-02-12 09:07:54

A quick and pretty solution (probably not the most efficient)

const data = [1, 2, 3, 4, 5, 6];
const randomizedData = data
  .map(d => ({r: Math.random(), d}))
  .sort((a, b) => a.r - b.r)
  .map(d => d.d);


@user11748403 2020-01-18 04:40:54

Community says arr.sort((a, b) => 0.5 - Math.random()) isn't 100% random!
yes! I tested and recommend do not use this method!

let arr = [1, 2, 3, 4, 5, 6]
arr.sort((a, b) => 0.5 - Math.random());

But I am not sure. So I Write some code to test !...You can also Try ! If you are interested enough!

let data_base = []; 
for (let i = 1; i <= 100; i++) { // push 100 time new rendom arr to data_base!
    [1, 2, 3, 4, 5, 6].sort((a, b) => {
      return  Math.random() - 0.5;     // used community banned method!  :-)      
} // console.log(data_base);  // if you want to see data!
let analysis = {};
for (let i = 1; i <= 6; i++) {
  analysis[i] = Array(6).fill(0);
for (let num = 0; num < 6; num++) {
  for (let i = 1; i <= 100; i++) {
    let plus = data_base[i - 1][num];
    analysis[`${num + 1}`][plus-1]++;
console.log(analysis); // analysed result 

In 100 different random arrays. (my analysed result)

{ player> 1   2   3  4   5   6
   '1': [ 36, 12, 17, 16, 9, 10 ],
   '2': [ 15, 36, 12, 18, 7, 12 ],
   '3': [ 11, 8, 22, 19, 17, 23 ],
   '4': [ 9, 14, 19, 18, 22, 18 ],
   '5': [ 12, 19, 15, 18, 23, 13 ],
   '6': [ 17, 11, 15, 11, 22, 24 ]
// player 1 got > 1(36 times),2(15 times),...,6(17 times)
// ... 
// ...
// player 6 got > 1(10 times),2(12 times),...,6(24 times)

As you can see It is not that much random ! soo... do not use this method!

If you test multiple times.You would see that player 1 got (number 1) so many times!
and player 6 got (number 6) most of the times!

@hakiko 2019-03-20 14:53:48

Edit: This answer is incorrect

See It is being left here for reference because the idea isn't rare.

//one line solution
shuffle = (array) => array.sort(() => Math.random() - 0.5);

let arr = [1, 2, 3];

Math.random() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.

@Sam Doidge 2019-11-27 17:56:25

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

@Sartheris Stormhammer 2020-02-19 08:24:46

Why minus 0.5? What does that number mean?

@Sam Doidge 2020-03-03 10:39:28

@SartherisStormhammer because we are using a compareFunction for the sort, and if that returns a number greater than 0, the elements being compared will ordered in direction only. -0.5 on Math.random() will give us a negative number ~50% of the time, which gives us the reverse order.

@deanwilliammills 2020-03-15 07:32:50

Straight forward and simplest solution. Thanks

@Redu 2017-08-30 18:10:58

Just to have a finger in the pie. Here i present a recursive implementation of Fisher Yates shuffle (i think). It gives uniform randomness.

Note: The ~~ (double tilde operator) is in fact behaves like Math.floor() for positive real numbers. Just a short cut it is.

var shuffle = a => a.length ? a.splice(~~(Math.random()*a.length),1).concat(shuffle(a))
                            : a;


Edit: The above code is O(n^2) due to the employment of .splice() but we can eliminate splice and shuffle in O(n) by the swap trick.

var shuffle = (a, l = a.length, r = ~~(Math.random()*l)) => l ? ([a[r],a[l-1]] = [a[l-1],a[r]], shuffle(a, l-1))
                                                              : a;

var arr = Array.from({length:3000}, (_,i) => i);

The problem is, JS can not coop on with big recursions. In this particular case you array size is limited with like 3000~7000 depending on your browser engine and some unknown facts.

@Kris Selbekk 2017-04-05 15:38:39

Edit: This answer is incorrect

See comments and It is being left here for reference because the idea isn't rare.

A very simple way for small arrays is simply this:

const someArray = [1, 2, 3, 4, 5];

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

It's probably not very efficient, but for small arrays this works just fine. Here's an example so you can see how random (or not) it is, and whether it fits your usecase or not.

const resultsEl = document.querySelector('#results');
const buttonEl = document.querySelector('#trigger');

const generateArrayAndRandomize = () => {
  const someArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  someArray.sort(() => Math.random() - 0.5);
  return someArray;

const renderResultsToDom = (results, el) => {
  el.innerHTML = results.join(' ');

buttonEl.addEventListener('click', () => renderResultsToDom(generateArrayAndRandomize(), resultsEl));
<button id="trigger">Generate</button>
<p id="results">0 1 2 3 4 5 6 7 8 9</p>

@DDD 2017-04-10 20:00:21

Nice one, but does generate a complete random elements every time?

@Kris Selbekk 2017-04-11 11:00:59

Not quite sure if I understood you correctly. This approach will indeed shuffle the array in a random way (albeit pseudo-random) every time you call the sort array - it's not a stable sort, for obvious reasons.

@AlexC 2017-06-23 10:41:18

For the same reasons as explained at . This is much more likely to leave early elements near the start of the array.

@Daniel Griscom 2017-11-03 18:48:18

This is a great, easy one-liner for when you need to scramble an array, but don't care too much about having the results be academically provably random. Sometimes, that last few inches to perfection take more time than it's worth.

@superluminary 2018-03-14 14:34:07

It would be lovely if this worked, but it doesn't. Because of the way quick-search works, an inconsistent comparator will be likely to leave array elements close to their original position. Your array will not be scrambled.

@Kris Selbekk 2018-03-16 13:09:44

Yet it is scrambled though. Try running [1,2,3,4,5].sort(() => Math.random() * 2 - 1); in the console, it'll scramble the result for every time. This isn't the perfect randomizer, but for simple use-cases it works just fine.

@Daniel Martin 2018-06-22 06:31:48

I don't think the comments here adequately warn how bad this method is if you want an even vaguely fair shuffle. Testing this method on chrome with an array of ten elements, the last element stays the last element HALF the time, and 75% of the time is in the last two. This isn't "academic" - it's really quite bad. OTOH, if you want to subtly make something that seems random but lets you cheat by often knowing characteristics of the supposedly shuffled list, I guess this could be used for that.

@Yevgen Gorbunkov 2019-06-25 08:29:55

We're still shuffling arrays in 2019, so here goes my approach, which seems neat and fast to me:

const src = [...'abcdefg'];

const shuffle = arr => 
  arr.reduceRight((res,_,__,arr) => 
    (res.push(arr.splice(0|Math.random()*arr.length,1)[0]), res),[]);

.as-console-wrapper {min-height: 100%}

@Rafi Henig 2019-06-05 16:37:07

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
    ren = Math.random();
    if (ren == 0.5) return 0;
    return ren > 0.5 ? 1 : -1

@Juzer Ali 2019-06-21 06:23:27

Is this unbiased?

@user151496 2019-11-02 02:04:16

what? this is so pointless. it has almost 0 chance of leaving the element intact (random generating exactly 0.5)

@Alex Szücs 2019-05-09 18:38:17

Rebuilding the entire array, one by one putting each element at a random place.

[1,2,3].reduce((a,x,i)=>{a.splice(Math.floor(Math.random()*(i+1)),0,x);return a},[])

var ia= [1,2,3];
var it= 1000;
var f = (a,x,i)=>{a.splice(Math.floor(Math.random()*(i+1)),0,x);return a};
var a = new Array(it).fill(ia).map(x=>x.reduce(f,[]));
var r = new Array(ia.length).fill(0).map((x,i)=>a.reduce((i2,x2)=>x2[i]+i2,0)/it)

console.log("These values should be quite equal:",r);

@ricks 2019-05-09 18:57:11

You should explain what your code is doing, some people may not understand 1 liners of this complexity.

@Sam Mason 2019-05-10 08:27:49

also note that due to the use of Math.round(... * i) this is biased, you want to be doing Math.floor(.. * (i+1)) instead

@Alex Szücs 2019-05-10 19:15:53

@SamMason Probablity of getting .5 is 1:1000000000000000000

@Sam Mason 2019-05-10 19:27:48

if you use round, the probability of selecting first and last index (i.e. 0 and n) are 0.5/n, the probability of selecting any other element is 1/n (where n = a.length). this is pretty bad for short arrays

@Alex Szücs 2019-05-10 20:08:19

@SamMason thank you for pointing the error, I have updated the answer and made a tester too

@Mubeen Khan 2019-04-17 22:02:07

Shuffle array of strings:

shuffle = (array) => {
  let counter = array.length, temp, index;
  while ( counter > 0 ) {
    index = Math.floor( Math.random() * counter );
    temp = array[ counter ];
    array[ counter ] = array[ index ];
    array[ index ] = temp;
  return array;

@HMR 2018-02-09 03:32:20

Funny enough there was no non mutating recursive answer:

var shuffle = arr => {
  const recur = (arr,currentIndex)=>{
      return arr;
    const randomIndex = Math.floor(Math.random() * currentIndex);
    const swap = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = swap;
    return recur(
      currentIndex - 1
  return recur(>x),arr.length-1);

var arr = [1,2,3,4,5,[6]];

@Bergi 2018-02-09 04:08:54

Maybe there wasn't because it's pretty inefficient? :-P

@HMR 2018-02-09 06:48:13

@Bergi Correct, updated with first answer logic. Still need to copy the array for immutability. Added because this is flagged as the duplicate of a question asking for a function that takes an array and returned a shuffled array without mutating the array. Now the question actually has an answer the OP was looking for.

@Pawel 2019-04-11 13:58:00

Randomly either push or unshift(add in the beginning).

['a', 'b', 'c', 'd'].reduce((acc, el) => {
  Math.random() > 0.5 ? acc.push(el) : acc.unshift(el);
  return acc;
}, []);

@Tophe 2013-08-09 15:37:42

var shuffle = function(array) {
   temp = [];
   originalLength = array.length;
   for (var i = 0; i < originalLength; i++) {
   return temp;

@davidatthepark 2016-05-19 22:17:35

This is obviously not as optimal as the Fisher-Yates algorithm, but would it work for technical interviews?

@Charlie Wallace 2019-03-20 16:41:23

@Andrea The code was broken due to the fact that array length is changed inside the for loop. With the last edit this is corrected.

@Hafizur Rahman 2018-04-01 12:15:07

Though there are a number of implementations already advised but I feel we can make it shorter and easier using forEach loop, so we don't need to worry about calculating array length and also we can safely avoid using a temporary variable.

var myArr = ["a", "b", "c", "d"];

myArr.forEach((val, key) => {
  randomIndex = Math.ceil(Math.random()*(key + 1));
  myArr[key] = myArr[randomIndex];
  myArr[randomIndex] = val;
// see the values
console.log('Shuffled Array: ', myArr)

@iPhoney 2018-12-21 06:45:59

For those of us who are not very gifted but have access to the wonders of lodash, there is such a thing as lodash.shuffle.

@abumalick 2017-05-19 13:23:11

A simple modification of CoolAJ86's answer that does not modify the original array:

 * Returns a new array whose contents are a shuffled copy of the original array.
 * @param {Array} The items to shuffle.
const shuffle = (array) => {
  let currentIndex = array.length;
  let temporaryValue;
  let randomIndex;
  const newArray = array.slice();
  // While there remains elements to shuffle...
  while (currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    // Swap it with the current element.
    temporaryValue = newArray[currentIndex];
    newArray[currentIndex] = newArray[randomIndex];
    newArray[randomIndex] = temporaryValue;
  return newArray;

@thomas-peter 2018-10-03 10:45:10

A functional solution using Ramda.

const {map, compose, sortBy, prop} = require('ramda')

const shuffle = compose(
  map(v => ({v, i: Math.random()}))


@Xavier Guihot 2018-08-06 21:35:08

d3.js provides a built-in version of the Fisher–Yates shuffle:

console.log(d3.shuffle(["a", "b", "c", "d"]));
<script src=""></script>

d3.shuffle(array[, lo[, hi]]) <>

Randomizes the order of the specified array using the Fisher–Yates shuffle.

@Evgenia Manolova 2018-01-13 23:16:03

a shuffle function that doesn't change the source array

Update: Here I'm suggesting a relatively simple (not from complexity perspective) and short algorithm that will do just fine with small sized arrays, but it's definitely going to cost a lot more than the classic Durstenfeld algorithm when you deal with huge arrays. You can find the Durstenfeld in one of the top replies to this question.

Original answer:

If you don't wish your shuffle function to mutate the source array, you can copy it to a local variable, then do the rest with a simple shuffling logic.

function shuffle(array) {
  var result = [], source = array.concat([]);

  while (source.length) {
    let index = Math.floor(Math.random() * source.length);
    source.splice(index, 1);

  return result;

Shuffling logic: pick up a random index, then add the corresponding element to the result array and delete it from the source array copy. Repeat this action until the source array gets empty.

And if you really want it short, here's how far I could get:

function shuffle(array) {
  var result = [], source = array.concat([]);

  while (source.length) {
    let index = Math.floor(Math.random() * source.length);
    result.push(source.splice(index, 1)[0]);

  return result;

@user9315861 2018-07-09 04:49:23

This is essentially the original Fisher-Yates algorithm, with your splice being a horribly inefficient way to do what they called "striking out". If you don't want to mutate the original array, then just copy it, and then shuffle that copy in place using the much more efficient Durstenfeld variant.

@Evgenia Manolova 2018-07-20 11:10:21

@torazaburo, thank you for your feedback. I've updated my answer, to make it clear that I'm rather offering a nice-looking solution, than a super-scaling one

@Taiga 2019-04-21 12:14:54

We could also use the splice method to create a copy like so: source = array.slice();.

@Tính Ngô Quang 2018-06-20 06:59:22

You can do it easily with:

// array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
// random
fruits.sort(function(a, b){return 0.5 - Math.random()});
// out

Please reference at JavaScript Sorting Arrays

@user9315861 2018-07-08 07:27:11

This algorithm has long been proven to be defective.

@Tính Ngô Quang 2018-07-09 05:14:18

Please prove to me. I based on w3schools

@user9315861 2018-07-09 09:09:39

You could read the thread at, or at W3schools has always been, and remains, a horrible source of information.

@Charlie Wallace 2019-03-20 17:12:03

For a good discussion on why this is not a good approach see…

@Syed Ayesha Bebe 2018-04-23 13:10:43

By using shuffle-array module you can shuffle your array . Here is a simple code of it .

var shuffle = require('shuffle-array'),
 //collection = [1,2,3,4,5];
collection = ["a","b","c","d","e"];


Hope this helps.

@icl7126 2018-03-15 18:14:29

Modern short inline solution using ES6 features:

['a','b','c','d'].map(x => [Math.random(), x]).sort(([a], [b]) => a - b).map(([_, x]) => x);

(for educational purposes)

Related Questions

Sponsored Content

52 Answered Questions

[SOLVED] How to create GUID / UUID?

  • 2008-09-19 20:01:00
  • Jason Cohen
  • 1865152 View
  • 4227 Score
  • 52 Answer
  • Tags:   javascript guid uuid

95 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6853440 View
  • 8434 Score
  • 95 Answer
  • Tags:   javascript arrays

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

36 Answered Questions

[SOLVED] Create ArrayList from array

86 Answered Questions

[SOLVED] How do JavaScript closures work?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

3 Answered Questions

66 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4096459 View
  • 3532 Score
  • 66 Answer
  • Tags:   java random integer

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

Sponsored Content