Languages
[Edit]
EN

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

0 points
Created by:
MindOfMadness3
696

In this article, we would like to show you how to get unique random elements from an array in JavaScript.

Practical example

In this example, we create a reusable function that gets unique random elements from an array (by index).

To get items with random indexes 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);
        if (guardian.has(index)) {
            continue;
        }
        const element = array[index];
        guardian.add(index);
        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 values from array

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 - getting unique random elements from array (unique indexes)
  2. JavaScript - randomize unique elements from array (unique indexes)
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