shuffling in js

Solutions on MaxInterview for shuffling in js by the best coders in the world

showing results for - "shuffling in js"
Arsène
29 Aug 2019
1function shuffle(array) {
2  var currentIndex = array.length, temporaryValue, randomIndex;
3
4  // While there remain elements to shuffle...
5  while (0 !== currentIndex) {
6
7    // Pick a remaining element...
8    randomIndex = Math.floor(Math.random() * currentIndex);
9    currentIndex -= 1;
10
11    // And swap it with the current element.
12    temporaryValue = array[currentIndex];
13    array[currentIndex] = array[randomIndex];
14    array[randomIndex] = temporaryValue;
15  }
16
17  return array;
18}
19
20// Used like so
21var arr = [2, 11, 37, 42];
22shuffle(arr);
23console.log(arr);