Skip to content

Instantly share code, notes, and snippets.

@gerrard00
Created February 28, 2017 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrard00/b50d8ebfa366489ea9f63d1d4f15df21 to your computer and use it in GitHub Desktop.
Save gerrard00/b50d8ebfa366489ea9f63d1d4f15df21 to your computer and use it in GitHub Desktop.
Randomly process an array
const input = ['I', 'come', 'from', 'mars'];
// if you don't want to change the array
let i = 0;
// roughly shuffle the indexes
const shuffledIndexes = input.map(() => i++).sort(i => Math.random() * 3 + -1);
for(let j = 0; j < input.length; j++) {
console.log(input[shuffledIndexes[j]]);
}
// or if you don't mind sorting the actual array
input.sort(i => Math.random() * 3 + -1).forEach(input => console.log(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment