Open In App

How to get a Random Element from an Array using Lodash ?

Last Updated : 03 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, when you have an array and need to select a random element from it, you can achieve this easily using the Lodash library. Lodash provides a variety of utility functions to simplify common programming tasks, including selecting random elements from arrays. Let’s explore how to accomplish this using Lodash.

Installing the Lodash library using the below command:

npm i lodash

Using _.sample method

In this approach, we are using _.sample from the Lodash library to randomly select an element from the array, and then we log the selected element res to the console.

Syntax:

_.sample( collection );

Example: The below example uses the _.sample method to get a random element from an array using Lodash.

JavaScript
const _ = require('lodash');
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const res = _.sample(array);
console.log(res);

Output:

3

Using _.random method

In this approach, we use _.random from Lodash to generate a random index within the range of the array length, then assign the element at that index to res, and finally log res to the console.

Syntax:

_.random([lower = 0], [upper = 1], [floating]);

Example: The below example uses _.random method to get a random element from an array using Lodash.

JavaScript
const _ = require('lodash');
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const randomIndex = _.random(array.length - 1);
const res = array[randomIndex];
console.log(res);

Output:

6

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads