Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if javascript array contains value using underscorejs

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

like image 489
ThomasD Avatar asked Aug 13 '26 15:08

ThomasD


2 Answers

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'; 
});
like image 172
Gabe Moothart Avatar answered Aug 16 '26 08:08

Gabe Moothart


I know this is late, but even easier:

var cars = [{ name:"Toyota Minivan", id:"506"}, { name:"Honda Civic", id:"619"}];

function findById(id) {
  return _.contains(_.pluck(cars, 'id'), id);
}
like image 22
justin Avatar answered Aug 16 '26 09:08

justin