Alex Rivera | Logout

IndexOf element in js array using a truth function using underscore or jquery

Asked 2011-11-01T15:48:16.213
9

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;
}
Edit
Report

1 Answer

2

It would be more efficient to do the for loop yourself and use break; (or return) to leave the loop once you've found the index.

for (var i = 0; i < arr.length; i++) {
    if (filter(arr[i])) {
        return i;
    }
}
answered 2011-11-01T16:01:06.927

Your Answer