1

Suppose I have an array of objects:

var a = [
    {id: "1", "name": "ABC"}, 
    {id: "2", "name": "XYZ"},
    {id: "3", "name": "PQR"},
    {id: "4", "name": "JKL"}
];

I need to find the index of object which has the key "id: '3' " in it. Is there any way to find the index of the object using underscore library? I have achieved this using for loop, but want to know an easier approach.

1
  • _.findIndex perhaps? Commented Dec 11, 2015 at 19:52

1 Answer 1

1

In ECMAScript 6 you can use findIndex:

[
    {id: "1", "name": "ABC"}, 
    {id: "2", "name": "XYZ"},
    {id: "3", "name": "PQR"},
    {id: "4", "name": "JKL"}
].findIndex(o => o.id === "3"); // 2

Similarly, underscore also has _.findIndex:

_.findIndex([
    {id: "1", "name": "ABC"}, 
    {id: "2", "name": "XYZ"},
    {id: "3", "name": "PQR"},
    {id: "4", "name": "JKL"}
], function(o){ return o.id === "3"}); // 2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.