Created
August 15, 2020 16:44
-
-
Save akhal3d96/b0175de0813590ccbc2eeae10aca2e92 to your computer and use it in GitHub Desktop.
Shuffle a Javascript Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Randomize the order of the elements in a given array. | |
* source: https://github.com/pazguille/shuffle-array/blob/master/dist/shuffle-array.js | |
* @param {Array} arr - The given array. | |
* @returns {Array} | |
*/ | |
export function shuffle (arr) { | |
if (!Array.isArray(arr)) { | |
throw new Error('shuffle expect an array as parameter.') | |
} | |
const rng = Math.random | |
const collection = arr.slice() | |
let len = arr.length | |
let random, temp | |
while (len) { | |
random = Math.floor(rng() * len) | |
len -= 1 | |
temp = collection[len] | |
collection[len] = collection[random] | |
collection[random] = temp | |
} | |
return collection | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment