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().
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