Skip to content

Instantly share code, notes, and snippets.

@thiamsantos
Created June 15, 2018 17:43
Show Gist options
  • Save thiamsantos/8492da2c75385ef3ec689f5b510f72e9 to your computer and use it in GitHub Desktop.
Save thiamsantos/8492da2c75385ef3ec689f5b510f72e9 to your computer and use it in GitHub Desktop.
array shuffle in js
function shuffle(arr) {
const {acc} = arr.reduce(
({acc, current}) => {
const index = Math.round(Math.random() * (current.length - 1))
const item = current[index]
current.splice(index, 1)
return {acc: [...acc, item], current}
},
{acc: [], current: [...arr]}
)
return acc
}
const original = [1, 2, 3, 4, 5]
console.log({original})
console.log({shuffle: shuffle(original)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment