Clue Mediator

How to get a number of random elements from an array in JavaScript

📅July 18, 2022

Today we will show you how to get a number of random elements from an array in JavaScript.

In the previous article, we have explained how to get a random value from an array in JavaScript. But here we will get the random n number of items from an array using JavaScript.

Way to get a number of random elements from an array

  1. Using sort() and Math.random() function
  2. Using lodash library
  3. Using non-destructive function

Before we start, let’s assume that we have the following array and we want to retrieve a random `3` items from an array.

var colors = [
    'Yellow',
    'Blue',
    'Pink',
    'Red',
    'Black',
    'White',
    'Green'
];

1. Using sort() and Math.random() function

In this method, we have to use the sort() and Math.random() functions to get the random elements. It’s one-liner unique solutions.

colors.sort(() => Math.random() - Math.random()).slice(0, 3);

// Output:
// ['Blue', 'Black', 'Green']

2. Using lodash library

We can also use the lodash library to get the random elements from the list.

_.sampleSize(colors, 3);

// Output:
// ['White', 'Green', 'Red']

3. Using non-destructive function

Let’s use the non-desctructive function to achieve the same output.

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
    return result;
}

getRandom(colors, 3);

// Output:
// ['Red', 'Yellow', 'White']

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂