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!
The javascript array method filter returns a subset of the array that return true from the function passed.
Here comes the coffeescript version of nrabinowitz's code.
using underscore I came up with something copied from their find implementation using _.any:
What do you think - do you have any better solutions?
There's a standard function in ECMAScript 2015 for
Array.prototype.findIndex()
. Currently it's implemented in all major browsers apart from Internet Explorer.Here's a polyfill, courtesy of the Mozilla Developer Network:
Here's the Underscore way to do it - this augments the core Underscore function with one that accepts an iterator function:
You could do something like this:
Regarding Christian's comment: if you override a standard JavaScript method with a custom one with
a differentthe same signature and different functionality, bad thing will likely happen. This is especially true if you're pulling in 3rd party libraries which may depend on the original, say, Array.proto.indexOf. So yeah, you probably want to call it something else.