Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the index of an object inside a Array using underscore.js?

I want to get the index of the given value inside a Array using underscore.js.

Here is my case

var array = [{'id': 1, 'name': 'xxx'},
             {'id': 2, 'name': 'yyy'},
             {'id': 3, 'name': 'zzz'}];

var searchValue = {'id': 1, 'name': 'xxx'};

I used the following code,

var index = _.indexOf(array, function(data) { 
                alert(data.toSource()); //For testing purpose 
                return data === searchValue; 
            });

Also tried this too

var index = _.indexOf(array, {id: searchValue.id});

But it returns -1 . Since it does not enter into that function. So I didn't get that alert message.

Whats wrong with my code. Can anyone help me?

like image 815
prince Avatar asked Feb 03 '14 08:02

prince


2 Answers

i am using find index

 _.findIndex(array, searchValue); 
like image 96
ßãlãjî Avatar answered Oct 19 '22 05:10

ßãlãjî


In case you have complicated objects, and want to search one object in the collection looking for a certain property, just go with:

 _.indexOf(arrayObj, _.findWhere(arrayObj, {id: 1})  );

Where "arrayObj" is the collection with objects, "id" is the prop, and "1" is the value being in search.

like image 32
Nicolae Lozovan Avatar answered Oct 19 '22 04:10

Nicolae Lozovan