I need where but with not case. For example, I would like to find plays, which have no name "Shakespeare":
_.where(listOfPlays, {author: !"Shakespeare", year: 1611});
^^^^^^^^^^^^^
NOT Shakespeare
How can I do it with underscore
?
I need where but with not case. For example, I would like to find plays, which have no name "Shakespeare":
_.where(listOfPlays, {author: !"Shakespeare", year: 1611});
^^^^^^^^^^^^^
NOT Shakespeare
How can I do it with underscore
?
4 Answers
Reset to default 11_.filter(listOfPlays, function(play) {
return play.author !== 'Shakespeare' && play.year === 1611;
});
http://underscorejs.org/#filter
where
is nothing more than a convenient wrapper around filter
:
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
https://github.com/jashkenas/underscore/blob/a6c404170d37aae4f499efb185d610e098d92e47/underscore.js#L249
You can cook your own "not where" version of _.where
like this
_.mixin({
"notWhere": function(obj, attrs) {
return _.filter(obj, _.negate(_.matches(attrs)));
}
});
And then you can write your code like this
_.chain(listOfPlays)
.where({
year: 1611
})
.notWhere({
author: 'Shakespeare'
})
.value();
Note: _.negate
is available only from v1.7.0. So, if you are using previous version of _
, you might want to do something like this
_.mixin({
"notWhere": function(obj, attrs) {
var matcherFunction = _.matches(attrs);
return _.filter(obj, function(currentObject) {
return !matcherFunction(currentObject);
});
}
});
Plenty of right answers, but technically the OP just asked about negating. You can also use reject, it's essentially the opposite of filter. To achieve the compound condition of 1611 and not Shakespeare:
_.reject(_.filter(listOfPlays, function(play){
return play.year === 1611
}), function(play) {
return play.author === 'Shakespeare';
});
Try this:
_.filter(listOfPlays,function(i){
return i['author']!='Shakespeare' && i['year']==1611;
});