How to use _.findIndex() and _.nth() In Lodash

This approach uses two methods: _.findIndex() to find the index of the first object in an array that satisfies the condition and Lodash’s to retrieve the object at a specific index.

Syntax:

_.findIndex(array, [predicate=_.identity], fromIndex);
_.nth(array, n);

Example: The example below shows how to use Lodash to Find and Return an Object from Array Using _.findIndex() and _.nth().

JavaScript
const _ = require('lodash');
const products = [
    { name: 'Headphones', price: 99.99 },
    { name: 'Laptop', price: 799.99 },
    { name: 'Mouse', price: 24.99 },
];

const laptopIndex = _.findIndex(products, 
                        product => product.name === 'Laptop');
if (laptopIndex !== -1) {
    const laptop = _.nth(products, laptopIndex);
    console.log(laptop);
}

Output:

{ name: 'Laptop', price: 799.99 }

How to use Lodash to Find & Return an Object from Array ?

JavaScript’s built-in array methods offer basic functionality whereas Lodash, a popular utility library, empowers developers with robust tools for complex array operations.

Below are the methods to find and return an object from array using Lodash:

Table of Content

  • Using _.find()
  • Using _.findIndex() and _.nth()
  • Using _.filter()

Run the command to install Loadsh:

npm i loadash

Similar Reads

Using _.find()

The _.find() is ideal for locating the first object in an array that satisfies a specific condition. It iterates through the array and returns the initial matching object. You can define the condition using a callback function or an object with key-value pairs representing the target object’s properties....

Using _.findIndex() and _.nth()

This approach uses two methods: _.findIndex() to find the index of the first object in an array that satisfies the condition and Lodash’s to retrieve the object at a specific index....

Using _.filter()

The _.filter() method extract objects from the “orders” array where the “status” property equals ‘pending’. It returns an array containing the filtered objects, representing pending orders....

Choosing the Right Method

For the first matching object use ‘_.find()’ for its simplicity and performance.For index and object: Utilize ‘_.findIndex()’ and ‘_.nth()’ when both the index and the object of the match are necessary.For processing multiple matches: Select ‘_.filter()’ if you plan subsequent operations on all matches, considering the new array creation....

Contact Us