Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  31] [ 7]  / answers: 1 / hits: 27075  / 11 Years ago, wed, november 20, 2013, 12:00:00

I have an array of cars like this:



[{ name:Toyota Minivan, id:506 }, { name:Honda Civic, id:619 }]


I am trying to check whether the array contains a certain id.



I have tried



var x =!!_.where(cars, {id:'506'}).length;


expecting it to return true if the array contains the id, but it always returns false.



What am I doing here ?



Btw, I don't have to use underscore.js if there is a better way of doing this.



thanks
Thomas


More From » arrays

 Answers
31

Your code does work (once you fix the syntax errors in the object array):
http://jsfiddle.net/ArPCa/



var cars = [{ name:Toyota Minivan, id:506}, { name:Honda Civic, id:619}];
var x =!!_.where(cars, {id:'506'}).length;
console.log('value: ' + x);


returns value: true. So there must be a problem somewhere else.



But, a better way to do this might be some:



var y = _.some(cars, function(c) {
return c.id == '506';
});

[#74154] Tuesday, November 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ira

Total Points: 298
Total Questions: 112
Total Answers: 103

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
;