Math.random(), there will be same occurrences. Which is not really "shuffling".
We have an array with
["a", "b", "c", "d"]elements.
We can loop through the array while creating a random index to copy the randomly chosen element to a new array.
If we do not delete the copied element from the original array, there will be some not-wanted things going on there on the output.
There'll be duplicates and there are elements which weren't picked.
["c", "a", "a", "d"], or
["d", "b", "b", "b"], or
["a", "a", "c", "a"], etc.
To solve that,
we need to trim the old array reference after one element gets picked by the "random index".
Let me explain it with words before you see the coding.
We have the same array as above:
["a", "b", "c", "d"]. And we wanna shuffle the elements.
- Create a buffer-array to store the original array (clone it), so that nothing will happen to the original one.
Then create an empty array to store the shuffled elements.
- Loop through the buffer-array to randomly pick an element from it, then place that chosen element to the empty array. Then delete/remove that particular element from the buffer-array.
For instance, from that
["a", "b", "c", "d"], we generate random index of
1, which means, the element
"b"is chosen. Then the empty array will consist of
["b"]and the buffer-array will be
["a", "c", "d"].
And after that, the random index is also
1, no problem, because the buffer-array is different now. So, the chosen element (with index
["a", "c", "d"]will be
"c". Now, the "empty array" consists of
["b", "c"]and the buffer-array is
And so on.
As you can see in that looping sequence, the buffer-array length will decrease until it's empty, and the empty array length will increase and it will have the shuffled elements.
array, will be left intact.
shufflefunction above can be cascaded, like:
var four_shuffles = shuffle(shuffle(shuffle(shuffle(original_array))));To shuffle the original array four times.
You can compact/shorten this as you need to. These examples below are the "readable" versions.
As you can see on those four snippets above, I'm not trying to shorten the methods, so that you can read it.
Also, those examples above are fast for plenty of elements.
Anywho, the last looping method is using
forEach. It's introduced in ES5 (ECMAScript 5). It's like
More information about