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?
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.
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] .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With