Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@geraldfullam
Created January 7, 2020 15:08
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 geraldfullam/eb1da11044643b5cb7aee2f802f049b0 to your computer and use it in GitHub Desktop.
Save geraldfullam/eb1da11044643b5cb7aee2f802f049b0 to your computer and use it in GitHub Desktop.
Cycle array items by random index
function getRandomIndex(len) {
return Math.floor(Math.random() * Math.floor(len));
}
function cycleArray(arr, i) {
return arr.slice(i).concat(arr.slice(0, i))
}
function cycleArrayByRandomIndex() {
return cycleArray(arr, getRandomIndex(arr.length))
}
const arr = ['foo', 'bar', 'fizz', 'buzz']
console.log(cycleArrayByRandomIndex(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment