Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the array index of an object with a specific key value in underscore

In underscore, I can successfully find an item with a specific key value

var tv = [{id:1},{id:2}] var voteID = 2; var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; }); //data = { id: 2 } 

but how do I find what array index that object occurred at?

like image 669
mheavers Avatar asked Feb 07 '14 15:02

mheavers


People also ask

How do you find the index of an object in an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do I find the index of an object in a key?

To get an object's key by index, call the Object. keys() method to get an array of the objects keys and use bracket notation to access the key at the specific index, e.g. Object. keys(obj)[1] .

How do you find the index of a value in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.


1 Answers

findIndex was added in 1.8:

index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID }) 

See: http://underscorejs.org/#findIndex

Alternatively, this also works, if you don't mind making another temporary list:

index = _.indexOf(_.pluck(tv, 'id'), voteId); 

See: http://underscorejs.org/#pluck

like image 112
Ropez Avatar answered Sep 28 '22 05:09

Ropez