javascript
Lodash - Get index of array item based on some condition
To find an index of an array item based on some condition, you can use _.findIndex of lodash.
const users = [
{ 'user': 'John Deo', 'active': false },
{ 'user': 'Rick Grimes', 'active': false },
{ 'user': 'Negan', 'active': true }
];
//Find Index where user is - Rick Grimes
const index = _.findIndex(users, function (item) {
return item.user == 'Rick Grimes';
});
console.log("User index is : " + index)
// => 1
// Find item index using full object match
const index_2 = _.findIndex(users, { 'user': 'Negan', 'active': true });
console.log("Object index is : " + index_2);
// => 2
_.findIndex Lodash
You can get the index of an item that exists in an array. You can find the item using predicates - a function that invokes each iteration. The basic syntax of this method is as below.
_.findIndex(Array, Predicate, FromIndex=0)
The function returns item index if found else return -1.
Example Demo
Was this helpful?
Similar Posts
- Test every item of array against some condition in javascript
- Render item condition based React
- Lodash - Create a string from array elements join with some separator
- Lodash - Find item index from array by searching from the end
- Lodash - Get index of first occurence of an array value
- Remove items starting from last untill given condition is false Lodash
- Remove items begin from start until given condition is false Lodash