I was reading the documentation for inArray earlier this morning, and I love the idea of a cross-browser indexOf. It's pretty neat.
I sometimes deal with arrays of objects, though, so it would be neat to have the ability to use inArray to give the index of a particular object based on a function that you pass.
Example:
var arr = [{"foo": "bar"}, {"foo": "foo"}];
var index = $.inArray(function(obj) { // index === 0
return obj.foo === "bar";
}, arr);
Is there a better way to do something like this that I missed?
I know this breaks the native indexOf piece, but this can easily be worked around by using jQuery.isFunction
Something like:
function inArray(elem, array) {
return (jQuery.isFunction( elem ) ?
function(){
for ( var i = 0, length = array.length; i < length; i ++ ) {
if ( elem( array[ i ] ) ) {
return i;
}
}
return -1;
}
:
function(){
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
})();
}
Using this:
var arr = [{"foo": "foo"}, {"foo": bar"}];
jQuery.inArray(function(obj) { // returns 0;
return obj.foo === "foo";
}, arr);
jQuery.inArray(function(obj) { // returns 1;
return obj.foo === "bar";
}, arr);
jQuery.inArray(function(obj) { // returns -1;
return obj.foo === "not found";
}, arr);
jQuery.inArray("steve", ["lol","steve"]); // returns 1;
Just an idea. Obviously if there's a better or more efficient way to go about doing this, I'm all ears.
Thanks,
Matt