I want to shuffle an array of elements in JavaScript like these:
[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]
I want to shuffle an array of elements in JavaScript like these:
[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]
Use the modern version of the Fisher–Yates shuffle algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Using Object.defineProperty
(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr)
. The following will allow you to call arr.shuffle()
to shuffle the array arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
i !== j
? That should save a bit of time –
Scalawag return a;
? Is it simply to allow for things like shuffle(a).slice(...)
? –
St (i + 1)
in const j = Math.floor(Math.random() * (i + 1));
? Wouldn't Math.floor(Math.random() * i));
be better? –
Hawthorn j
is random, so no, you can't do that. However the loop could start at i = a.length / 2 + 1
. You don't have to shuffle the same items twice, indeed. –
Hipped i === j
, example i=j=2
then the code does [a[2], a[2]] = [a[2], a[2]]
. No point. And no, you need to iterate on all elements. Think about the case random returns always 1
. Your change wouldn't shuffle half of the array. –
Scalawag const
communicates intent clearly: "I declare that this variable will never be reassigned". That simplifies cognitive load for reading the code and adds expressiveness -- when you do use let
(on rare occasions), it communicates "this variable will be reassigned". const
by default generally makes for better-quality code, smaller functions, fewer pieces of mutable state to keep track of than let
-heavy, reassignment-happy code. –
Frizzle const obj = {}; obj.prop = 'value';
. let, on the other hand, is semantically consistent. –
Pharyngo You could use the Fisher-Yates Shuffle (code adapted from this site):
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
while
loop with a for
loop and turns counter > 0
into 0 < counter
. I'm not entirely sure what parts speed it up, but the end result is a tiny bit faster than the original. –
Ternary undefined
column. jsfiddle.net/tomasswood/z8zm7 –
Tribunate ~~
is even better than | 0
: index = ~~(Math.random() * counter)
–
Oren | 0
was marginally faster. –
Ternary let
s were replaced with const
as they aren't modified at all, except for counter
. –
Andvari © 2022 - 2024 — McMap. All rights reserved.
arr1.reduceRight((p,v,i,a)=>(v=i?~~(Math.random()*(i+1)):i, v-i?[a[v],a[i]]=[a[i],a[v]]:0, a),a)
; Also check out this function. – Pane