I need basically the same functionality as Underscore's find but with the index of the element as a result (and not the element itself).
As far as I know, Underscore's indexOf looks for a value and doesn't take a function. Same problem for jQuery's inArray function.
I came up with the following implementation, but I'm not sure it is the most efficient:
function myIndexOf(arr, filter) {
var index;
$.each(arr, function (i, elt) { if (filter(elt)) { index=i; return false; } });
return index;
}
_.findIndex
is available in Lo-Dash and Underscore.js:
var characters = [
{ 'name': 'barney', 'age': 36, 'blocked': false },
{ 'name': 'fred', 'age': 40, 'blocked': true },
{ 'name': 'pebbles', 'age': 1, 'blocked': false }
];
_.findIndex(characters, function(chr) {
return chr.age < 20;
});
// → 2
_.findIndex(characters, { 'age': 36 });
// → 0
_.findIndex(characters, { 'name': 'dino' });
// → -1 (not found)
Here is a simple implementation:
function find(collection, filter) {
for (var i = 0; i < collection.length; i++) {
if(filter(collection[i], i, collection)) return i;
}
return -1;
}
It will work on any indexable object that has a length property, and you can pass a complex filter function of the form filter(element, index, collection)
(optional parameters).
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