Sunday, May 19, 2024
71
rated 0 times [  76] [ 5]  / answers: 1 / hits: 32976  / 12 Years ago, mon, september 10, 2012, 12:00:00

I need the index of the first value in the array, that matches a custom compare function.



The very nice underscorej has a find function that returns the first value where a function returns true, but I would need this that returns the index instead. Is there a version of indexOf available somewhere, where I can pass a function used to comparing?



Thanks for any suggestions!


More From » underscore.js

 Answers
6

Here's the Underscore way to do it - this augments the core Underscore function with one that accepts an iterator function:



// save a reference to the core implementation
var indexOfValue = _.indexOf;

// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({

// return the index of the first array element passing a test
indexOf: function(array, test) {
// delegate to standard indexOf if the test isn't a function
if (!_.isFunction(test)) return indexOfValue(array, test);
// otherwise, look for the index
for (var x = 0; x < array.length; x++) {
if (test(array[x])) return x;
}
// not found, return fail value
return -1;
}

});

_.indexOf([1,2,3], 3); // 2
_.indexOf([1,2,3], function(el) { return el > 2; } ); // 2

[#83153] Saturday, September 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julissaimana

Total Points: 593
Total Questions: 108
Total Answers: 112

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;