EN
JavaScript - get unique random values from array
0
points
In this article, we would like to show you how to get unique random values from an array in JavaScript.
Practical example
In this example, we create a reusable function that gets random unique elements from an array (by index).
To get random items from array we use the Math.random() method and to ensure their uniqueness we use Set.
// ONLINE-RUNNER:browser;
const randomizeIndex = (count) => {
return Math.floor(count * Math.random());
};
const randomizeElemnts = (array, count) => {
if (count > array.length) {
throw new Error('Array size cannot be smaller than expected random numbers count.');
}
const result = [];
const guardian = new Set();
while (result.length < count) {
const index = randomizeIndex(count);
const element = array[index];
if (guardian.has(element)) {
continue;
}
guardian.add(element);
result.push(element);
}
return result;
};
// Usage example:
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const element = randomizeElemnts(array, 5);
console.log(element); // Example output: [2, 0, 4, 3, 1]