Languages
[Edit]
EN

JavaScript - get unique random values from array

0 points
Created by:
Kevin
797

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]

 

See also

  1. JavaScript - get multiple random elements from array

  2. JavaScript - get unique random elements from array (unique indexes)

References

  1. Math.random() - JavaScript | MDN
  2. Math.floor() - JavaScript | MDN
  3. Set.prototype.has() - JavaScript | MDN
  4. Set.prototype.add() - JavaScript | MDN

Alternative titles

  1. JavaScript - randomize unique values from array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join