How to get a random element from an array
Short answer
Multiply Math.random() by the length and round down to get a valid index:
const colors = ['red', 'green', 'blue'];
const color = colors[Math.floor(Math.random() * colors.length)];
console.log(colors.includes(color));Output:
trueSeveral without repeats
Shuffle a copy of the array and take the first elements:
const shuffle = (array) => {
const copy = [...array];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
};
const winners = shuffle(['Anna', 'Oleg', 'Maria', 'Ivan', 'Olga']).slice(0, 2);
console.log(winners.length, new Set(winners).size);Output:
2 2Common mistake
Math.round() instead of Math.floor() sometimes gives an index equal to the length, and the result is undefined:
const colors = ['red', 'green', 'blue'];
console.log(colors[Math.round(0.9 * colors.length)]);Output:
undefinedFunctions used in this recipe
- Math.random — Returns a random number between 0 and 1.
- Math.floor — Rounds a number down to an integer.