How to use _.findIndex and _.nth methods In Lodash
In this approach, we are using the _.findIndex() method from lodash to determine the index of the object in the array ‘arr‘ where the ‘name‘ property matches ‘w3wiki‘. Then, we use _.nth() to get the object at that index.
Syntax:
_.findIndex(array, [predicate=_.identity], fromIndex);
_.nth(array, n);
Example: The below example uses _.findIndex and _.nth methods to find and return an object from Array.
const _ = require('lodash');
const arr = [
{
id: 1, name: 'w3wiki',
category: 'Education'
},
{
id: 2, name: 'Stack Overflow',
category: 'Q&A'
},
{
id: 3, name: 'GitHub',
category: 'Development'
}
];
function approach2Fn(arr, key, value) {
const ind = _.findIndex(arr, [key, value]);
if (ind !== -1) {
return _.nth(arr, ind);
} else {
return null;
}
}
const res = approach2Fn(arr, 'name',
'w3wiki');
console.log(res);
Output:
{ id: 1, name: 'w3wiki', category: 'Education' }
How to use Lodash to find & Return an Object from Array ?
In JavaScript, the Lodash Module has different methods of doing and get objects from the array. we will explore three different methods with practical implementation of each approach in terms of examples and output to to find and return an object from Array.
These are the following methods:
Table of Content
- Using _.find() method
- Using _.findIndex and _.nth methods
- Using _.filter() method