Sometimes, we want to randomly select array item without repeats with JavaScript.
In this article, we’ll look at how to randomly select array item without repeats with JavaScript.
How to randomly select array item without repeats with JavaScript?
To randomly select array item without repeats with JavaScript, we can shuffle the array and then return the number of items we want from the shuffled array.
For instance, we write:
const arr = ["Roger", "Russell", "Clyde", "Egbert", "Clare", "Bobbie", "Simon", "Elizabeth", "Ted", "Caroline"];
const choices = arr.sort(() => Math.random() - 0.5).slice(0, 5)
console.log(choices);
to call arr.sort
with a callback that return a number between -0.5 and 0.5 to return the shuffled version of arr
.
And then we call slice
with 0 and 5 to return the first 5 elements from the shuffled array.
Therefore, choices
is something like ["Egbert", "Elizabeth", "Simon", "Clare", "Caroline"]
.
Conclusion
To randomly select array item without repeats with JavaScript, we can shuffle the array and then return the number of items we want from the shuffled array.