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?
This is to help
lodash
users. check if your key is present by doing:If your target environment supports ES2015 (or you have a transpile step, eg with Babel), you can use the native Array.prototype.findIndex().
Given your example
If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.
Method 1
Since the predicate for
_.find
receives both the value and index of an element, you can use side effect to retrieve the index, like this:Method 2
Looking at underscore source, this is how
_.find
is implemented:To make this a
findIndex
function, simply replace the lineresult = value;
withresult = index;
This is the same idea as the first method. I included it to point out that underscore uses side effect to implement_.find
as well.I don't know if there is an existing underscore method that does this, but you can achieve the same result with plain javascript.
Then you can just do:
var data = tv[tv.getIndexBy("id", 2)]
Keepin' it simple:
Or, for non-haters, the CoffeeScript variant:
you can use
indexOf
method fromlodash