Get random element from array when looping
When looping over an array in JavaScript, you sometimes want to get a random item.
One solution is to first shuffle the array and then loop over it.
Another one is to get random element while looping.
Lets say that you want to render a word cloud.
Lets say that you do not want to keep the same order each time.
This is where you can use the randomSplice
function.
yarn add random-splice
or
npm i random-splice
import { randomSplice } from 'random-splice';
const arr = ['Your', 'Awesome', 'Array'];
while (arr.length) {
console.log(randomSplice(arr));
}
MIT