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
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 2 3 4 5 6 7 8 9 | 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.
1 2 3 4 | 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.
1 2 3 4 | _.sampleSize(colors, 3); // Output: // ['White', 'Green', 'Red'] |
3. Using non-destructive function
Let’s use the non-desctructive function to achieve the same output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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..!! 🙂