Tyler
Tyler

Reputation: 839

Underscore.js, testing if entire array is in another array

A little new to Underscore.js here. I'm trying filter an array of objects by testing whether all items in a tags array are present in an object's tags.

So something like this, using Underscore's filter and every methods:

/* the set of data */
var colors = [
  {
    "id": "001",
    "tags": ["color_family_white", "tone_warm", "room_study"]
  }, 
  {
    "id": "002",
    "tags": ["color_family_white", "tone_neutral"]
  },
  {
    "id": "003",
    "tags": ["color_family_red", "tone_bright", "room_kitchen"]
  }
];

/* an example of white I might want to filter on */
var tags = ["color_family_white", "room_study"];

var results = _.filter(colors, function (color) {
    return _.every(tags, function() { /* ??? what to do here */} );
});

All tags should be present on color.tags. So this should return only color 001.

This shows roughly what I'm trying to do: http://jsfiddle.net/tsargent/EtuS7/5/

Upvotes: 2

Views: 36

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149010

Using indexOf would work:

var results = _.filter(colors, function (color) {
    return _.every(tags, function(tag) { return _.indexOf(color.tags, tag) > -1; } );
});

Or the built-in indexOf function:

var results = _.filter(colors, function (color) {
    return _.every(tags, function(tag) { return color.tags.indexOf(tag) > -1; } );
});

But for brevity, you could also use the difference function:

var results = _.filter(colors, function (color) {
    return _.difference(tags, color.tags).length === 0;
});

Demonstration

Upvotes: 3

Related Questions