Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  21] [ 3]  / answers: 1 / hits: 52379  / 11 Years ago, mon, february 3, 2014, 12:00:00

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?


More From » angularjs

 Answers
4

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.


[#72771] Saturday, February 1, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
khalidkendelld

Total Points: 55
Total Questions: 99
Total Answers: 77

Location: South Korea
Member since Tue, Feb 22, 2022
2 Years ago
;