Skip to content

Instantly share code, notes, and snippets.

@akhal3d96
Created August 15, 2020 16:44
Show Gist options
  • Save akhal3d96/b0175de0813590ccbc2eeae10aca2e92 to your computer and use it in GitHub Desktop.
Save akhal3d96/b0175de0813590ccbc2eeae10aca2e92 to your computer and use it in GitHub Desktop.
Shuffle a Javascript Array
/**
* 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