2

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/

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.