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

0

Issue

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?

Solution

Use this instead:

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

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

_.each(array, function(data, idx) { 
   if (_.isEqual(data, searchValue)) {
      index = idx;
      return;
   }
});

console.log(index); //0

In your snippet data === searchValue compares the objects’ references, you don’t want to do this. On the other hand, if you use data == searchValue you are going to compare objects’ string representations i.e. [Object object] if you don’t have redefined toString methods.

So the correct way to compare the objects is to use _.isEqual.

Answered By – Minko Gechev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More