Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Last active June 30, 2018 11:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loretoparisi/c09e131d0b731c64fff498b288eba78e to your computer and use it in GitHub Desktop.
Save loretoparisi/c09e131d0b731c64fff498b288eba78e to your computer and use it in GitHub Desktop.
Shuffle Array in JavaScript
/**
* Shuffle array
* Fisher-Yates (aka Knuth) Shuffle
*/
let shuffle = (array) => {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
@loretoparisi
Copy link
Author

@loretoparisi
Copy link
Author

Example:

shuffle([...Array(10).keys()])
shuffle([...Array(1000).keys()])

Performances:

var t0,t1;

t0 = performance.now();
shuffle([...Array(10).keys()])
t1 = performance.now();
console.log("10:"+(t1 - t0) + " msec.")

t0 = performance.now();
shuffle([...Array(100).keys()])
t1 = performance.now();
console.log("100:"+(t1 - t0) + " msec.")

t0 = performance.now();
shuffle([...Array(1000).keys()])
t1 = performance.now();
console.log("1000:"+(t1 - t0) + " msec.")

t0 = performance.now();
shuffle([...Array(10000).keys()])
t1 = performance.now();
console.log("10000:"+(t1 - t0) + " msec.")

t0 = performance.now();
shuffle([...Array(100000).keys()])
t1 = performance.now();
console.log("100000:"+(t1 - t0) + " msec.")

t0 = performance.now();
shuffle([...Array(1000000).keys()])
t1 = performance.now();
console.log("1000000:"+(t1 - t0) + " msec.")
86.6999999852851 msec.
10:0.10000000474974513 msec.
100:0 msec.
1000:0.20000000949949026 msec.
10000:2.199999988079071 msec.
100000:18.099999986588955 msec.
1000000:100.19999998621643 msec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment