Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 339
nakhli Avatar asked Nov 01 '11 15:11

nakhli


2 Answers

_.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)
like image 194
Paolo Moretti Avatar answered Sep 19 '22 19:09

Paolo Moretti


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).

like image 35
Luc125 Avatar answered Sep 18 '22 19:09

Luc125