Created
June 15, 2018 17:43
-
-
Save thiamsantos/8492da2c75385ef3ec689f5b510f72e9 to your computer and use it in GitHub Desktop.
array shuffle in js
This file contains hidden or 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
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