#### [SOLVED] How to randomize (shuffle) a JavaScript array?

I have an array like this:

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

How can I randomize / shuffle it? #### @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!
data_base.push(
[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! # Edit: This answer is incorrect

See https://stackoverflow.com/a/18650169/28234. It is being left here for reference because the idea isn't rare.

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

//Demo
let arr = [1, 2, 3];
shuffle(arr);
``````

`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);
`````` #### @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;

console.log(JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])));``````

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);
console.time("shuffle");
shuffle(arr);
console.timeEnd("shuffle");``````

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. # Reliable, Effecient, Short

Some solutions on this page aren't reliable (they only partially randomise the array). Other solutions are significantly less effecient. With `testShuffleArrayFun` (see below) we can test array shuffling functions for reliability and performance. The following solutions are: reliable, effecient and short (using ES6 syntax)

[Comparison tests were done using `testShuffleArrayFun` against other solutions, in Google Chrome]

Shuffle Array In place

``````    function getShuffledArr (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

As you can see in this page, there have been incorrect solutions offered here in the past. I wrote and have used the following function to test any pure (no side effects) array randomizing functions.

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

var countArr = arr.map(el=>{
return arr.map(
el=> 0
)
}) //   For each possible position in the shuffledArr and for
//   each possible value, we'll create a counter.
const t0 = performance.now()
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)
shuffledArr.forEach(
(value,key)=>{countArr[key][value]++}
)
}
const t1 = performance.now()
console.log(`Count Values in position`)
console.table(countArr)

const frequencyArr = countArr.map( positionArr => (
positionArr.map(
count => count/n
)
))

console.log("Frequency of value in position")
console.table(frequencyArr)
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 array.map

``````    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. #### @Kris Selbekk 2017-04-05 15:38:39

See comments and https://stackoverflow.com/a/18650169/28234. 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(' ');
};

``````<h1>Randomize!</h1>
<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. #### @Kris Selbekk 2017-04-27 12:53:18

I didn't quite understand the down-vote here - care to comment? =) #### @DDD 2017-04-27 15:00:25

Wasn't me, but however i dont understand why its downvoted either. #### @AlexC 2017-06-23 10:41:18

For the same reasons as explained at stackoverflow.com/a/18650169/28234 . 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)), res),[]);

console.log(shuffle(src));``````
``.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? #### @Rafi Henig 2019-06-22 23:13:25

No reason to believe otherwise. #### @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 );
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)=>{
console.log("What?",JSON.stringify(arr))
if(currentIndex===0){
return arr;
}
const randomIndex = Math.floor(Math.random() * currentIndex);
const swap = arr[currentIndex];
arr[currentIndex] = arr[randomIndex];
arr[randomIndex] = swap;
return recur(
arr,
currentIndex - 1
);
}
return recur(arr.map(x=>x),arr.length-1);
};

var arr = [1,2,3,4,5,];
console.log(shuffle(arr));
console.log(arr);`````` #### @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++) {
temp.push(array.splice(Math.floor(Math.random()*array.length),1));
}
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. #### @Laurens Holst 2012-09-28 20:20:11

Here is a JavaScript implementation of the Durstenfeld shuffle, a computer-optimized version of Fisher-Yates:

``````/**
* Randomize array element order 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;
}
}
``````

The Fisher-Yates algorithm works by picking one random element for each original array element, and then excluding it from the next draw. Just like randomly picking from a deck of cards.

This exclusion is done in a clever way (invented by Durstenfeld for use by computers) by swapping the picked element with the current element, and then picking the next random element from the remainder. For optimal efficiency, the loop runs backwards so that the random pick is simplified (it can always start at 0), and it skips the last element because there are no other choices anymore.

The running time of this algorithm is O(n). Note that the shuffle is done in-place. So if you do not want to modify the original array, make a copy of it first with `.slice(0)`.

## 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: ideone.com/pfRanN). 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 blog.codinghorror.com/the-danger-of-naivete 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 softwareonastring.com/1135/perils-of-copy-paste-programming 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. #### @user7776077 2018-03-24 12:46:55

this ES6 script works just perfect, thank you so much! #### @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. gist.github.com/nikolas/96586a0b56f53eabfd6fe4ed59fecb98 #### @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--) {...}` #### @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.
* https://stackoverflow.com/a/2450976/1673761
* https://stackoverflow.com/a/44071316/1673761
*/
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(prop('v')),
sortBy(prop('i')),
map(v => ({v, i: Math.random()}))
)

shuffle([1,2,3,4,5,6,7])
`````` #### @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="http://d3js.org/d3.v5.min.js"></script>``

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

Randomizes the order of the specified array using the Fisher–Yates shuffle. ### 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.

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);
result.push(source[index]);
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));
}

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();`. #### @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. #### @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 stackoverflow.com/a/18650169/7224430. 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. #### @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
console.log(fruits);``````

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 css-tricks.com/snippets/javascript/shuffle-array, or at news.ycombinator.com/item?id=2728914. 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 stackoverflow.com/questions/962802/… #### @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"];
shuffle(collection);

console.log(collection);
``````

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) #### @Mudlabs 2018-01-30 01:54:01

``````// Create a places array which holds the index for each item in the
// passed in array.
//
// Then return a new array by randomly selecting items from the
// passed in array by referencing the places array item. Removing that
// places item each time though.
function shuffle(array) {
let places = array.map((item, index) => index);
return array.map((item, index, array) => {
const random_index = Math.floor(Math.random() * places.length);
const places_value = places[random_index];
places.splice(random_index, 1);
return array[places_value];
})
}
`````` #### @Saksham Khurana 2018-01-29 10:06:33

I have written a shuffle function on my own . The difference here is it will never repeat a value (checks in the code for this) :-

``````function shuffleArray(array) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
newArray.push(-1);
}

for (var j = 0; j < array.length; j++) {
var id = Math.floor((Math.random() * array.length));
while (newArray[id] !== -1) {
id = Math.floor((Math.random() * array.length));
}

newArray.splice(id, 1, array[j]);
}
return newArray; }
`````` #### @Thomas Baruchel 2017-02-19 15:23:58

From a theoretical point of view, the most elegant way of doing it, in my humble opinion, is to get a single random number between 0 and n!-1 and to compute a one to one mapping from `{0, 1, …, n!-1}` to all permutations of `(0, 1, 2, …, n-1)`. As long as you can use a (pseudo-)random generator reliable enough for getting such a number without any significant bias, you have enough information in it for achieving what you want without needing several other random numbers.

When computing with IEEE754 double precision floating numbers, you can expect your random generator to provide about 15 decimals. Since you have 15!=1,307,674,368,000 (with 13 digits), you can use the following functions with arrays containing up to 15 elements and assume there will be no significant bias with arrays containing up to 14 elements. If you work on a fixed-size problem requiring to compute many times this shuffle operation, you may want to try the following code which may be faster than other codes since it uses `Math.random` only once (it involves several copy operations however).

The following function will not be used, but I give it anyway; it returns the index of a given permutation of `(0, 1, 2, …, n-1)` according to the one to one mapping used in this message (the most natural one when enumerating permuations); it is intended to work with up to 16 elements:

``````function permIndex(p) {
var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000];
var tail = [];
var i;
if (p.length == 0) return 0;
for(i=1;i<(p.length);i++) {
if (p[i] > p) tail.push(p[i]-1);
else tail.push(p[i]);
}
return p * fact[p.length-1] + permIndex(tail);
}
``````

The reciprocal of the previous function (required for your own question) is below; it is intended to work with up to 16 elements; it returns the permutation of order n of `(0, 1, 2, …, s-1)`:

``````function permNth(n, s) {
var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000];
var i, j;
var p = [];
var q = [];
for(i=0;i<s;i++) p.push(i);
for(i=s-1; i>=0; i--) {
j = Math.floor(n / fact[i]);
n -= j*fact[i];
q.push(p[j]);
for(;j<i;j++) p[j]=p[j+1];
}
return q;
}
``````

Now, what you want merely is:

``````function shuffle(p) {
var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000];
return permNth(Math.floor(Math.random()*fact[p.length]), p.length).map(
function(i) { return p[i]; });
}
``````

It should work for up to 16 elements with a little theoretical bias (though unnoticeable from a practical point of view); it can be seen as fully usable for 15 elements; with arrays containing less than 14 elements, you can safely consider there will be absolutely no bias. #### @Gershom 2018-01-24 17:34:05

Definitely elegant! #### @Daniel Martin 2015-06-25 15:25:25

I found this variant hanging out in the "deleted by author" answers on a duplicate of this question. Unlike some of the other answers that have many upvotes already, this is:

1. Actually random
2. Not in-place (hence the `shuffled` name rather than `shuffle`)
3. Not already present here with multiple variants
``````Array.prototype.shuffled = function() {
return this.map(function(n){ return [Math.random(), n] })
.sort().map(function(n){ return n });
}
`````` #### @WiredPrairie 2015-07-14 12:17:43

(I suspect it was deleted as it is a very inefficient way to randomize the array, especially for larger arrays... whereas the accepted answer, and a number of other clones of that answer randomize in-place). #### @Daniel Martin 2015-07-14 18:54:30

Yeah, but given that the well-known wrong answer is still up with a bunch of votes, an inefficient but correct solution should at least be mentioned. #### @Daniel Martin 2015-07-14 22:58:40

`[1,2,3,4,5,6].sort(function() { return .5 - Math.random(); });` - it doesn't give a random sort, and if you use it you can end up embarrassed: robweir.com/blog/2010/02/microsoft-random-browser-ballot.htm‌​l #### @4castle 2017-11-10 14:39:53

You need to use `.sort(function(a,b){ return a - b; })` if you want the sort to compare values numerically. The default `.sort()` comparator is lexicographic, meaning it will consider `10` to be less than `2` since `1` is less than `2`. #### @Daniel Martin 2017-11-10 14:56:44

@4castle Okay, I updated the code, but am going to revert it: the distinction between lexicographic order and numerical order doesn't matter for numbers in the range that `Math.random()` produces. (that is, lexicographic order is the same as numeric order when dealing with numbers from 0 (inclusive) to 1 (exclusive)) #### @Marcin Malinowski 2017-09-23 21:33:39

All the other answers are based on Math.random() which is fast but not suitable for cryptgraphic level randomization.

The below code is using the well known `Fisher-Yates` algorithm while utilizing `Web Cryptography API` for cryptographic level of randomization.

``````var d = [1,2,3,4,5,6,7,8,9,10];

function shuffle(a) {
var x, t, r = new Uint32Array(1);
for (var i = 0, c = a.length - 1, m = a.length; i < c; i++, m--) {
crypto.getRandomValues(r);
x = Math.floor(r / 65536 / 65536 * m) + i;
t = a [i], a [i] = a [x], a [x] = t;
}

return a;
}

console.log(shuffle(d));`````` #### @Lievno 2017-04-14 09:41:30

``````function shuffleArray(array) {
// Create a new array with the length of the given array in the parameters
const newArray = array.map(() => null);

// Create a new array where each index contain the index value
const arrayReference = array.map((item, index) => index);

// Iterate on the array given in the parameters
array.forEach(randomize);

return newArray;

function randomize(item) {
const randomIndex = getRandomIndex();

// Replace the value in the new array
newArray[arrayReference[randomIndex]] = item;

// Remove in the array reference the index used
arrayReference.splice(randomIndex,1);
}

// Return a number between 0 and current array reference length
function getRandomIndex() {
const min = 0;
const max = arrayReference.length;
return Math.floor(Math.random() * (max - min)) + min;
}
}

console.log(shuffleArray([10,20,30,40,50,60,70,80,90,100]));``````

### [SOLVED] How do I remove a particular element from an array in JavaScript?

• 2011-04-23 22:17:18
• Walker
• 6266956 View
• 7826 Score
• Tags:   javascript arrays

### [SOLVED] Create GUID / UUID in JavaScript?

• 2008-09-19 20:01:00
• Jason Cohen
• 1702441 View
• 3980 Score
• Tags:   javascript guid uuid