Skip to content

Instantly share code, notes, and snippets.

@gabrielrufino
Last active January 20, 2020 17:51
Show Gist options
  • Save gabrielrufino/d535826bf4e4bd5efbd6b82a46650a60 to your computer and use it in GitHub Desktop.
Save gabrielrufino/d535826bf4e4bd5efbd6b82a46650a60 to your computer and use it in GitHub Desktop.
Shuffle the elements of an array
const shuffle = require('./shuffle')
const example = [1, 2, 3]
const shuffled = shuffle(example)
/*
shuffled can be any of these:
- [1, 2, 3]
- [1, 3, 2]
- [2, 1, 3]
- [2, 3, 1]
- [3, 1, 2]
- [3, 2, 1]
*/
function shuffle(array) {
const copy = [...array]
return copy.sort(() => Math.random() - 0.5)
}
module.exports = shuffle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment