user240993
user240993

Reputation:

With Underscorejs, how to find whether an array contains another array?

I have this

var matches = bookmarks.filter(function(x) {
    return _.contains(x.get("tags"), 'apple');
});

Which will return the bookmark objects that have the apple tags

I want to put an array there instead to pull and all the bookmarks that have the matching values, similar to this

var matches = bookmarks.filter(function(x) {
    return _.contains(x.get("tags"), ['apple','orange']);
});

This doesn't work, any way to get it to work?

EDIT: Im sorry, bookmarks is a collection and im trying to return the models that have the apple and orange tags

Upvotes: 22

Views: 31696

Answers (2)

epascarello
epascarello

Reputation: 207501

If tags is a string, your code it would be

return _.indexOf(x.get("tags"), ['apple','orange']) > -1;

Example with indexOf : jsFiddle

If tags is an array, you can use intersection

return _.intersection(['apple','orange'], x.get("tags")).length > 0;

Example with intersection: jsFiddle

Upvotes: 26

pimvdb
pimvdb

Reputation: 154828

There doesn't seem to be a function for that in underscore. However, you can easily combine other functions to accomplish this:

_.mixin({
  containsAny: function(arr, values) {
    // at least one (.some) of the values should be in the array (.contains)
    return _.some(values, function(value) {
      return _.contains(arr, value);
    });
  }
});

Upvotes: 5

Related Questions