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

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.

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.

2. Using lodash library

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

3. Using non-destructive function

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

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

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *