user1063192
user1063192

Reputation: 157

Angular Filter - Returning objects that every object in second array?

I am close, but need your help. I am trying to make filter that loops through 2 arrays, one is a list of articles and the other is a list of tags.

What I want to happen is if I have 3 tags, "nyc", "health-care", and "tech", I want the articles that contain ALL three tags. My current code returns any articles that contain any of the 3 tags.

.filter('selectedTags', function() {
    return function(articles, tags) {
        return articles.filter(function(article) {
            for (var i in article.article.tags) {
                for (var t in tags) {
                    if (tags[t].text === article.article.tags[i].text) {
                         return true;
                    }
                }
            }
            return false;
        });
    };
})

Upvotes: 0

Views: 58

Answers (1)

jimmious
jimmious

Reputation: 358

This should work..

.filter('selectedTags', function() {
return function(articles, tags) {
    return articles.filter(function(article) {
        var count = 0;
        for (var i in article.article.tags) {
            for (var t in tags) {
                if (tags[t].text === article.article.tags[i].text) {
                     count++;
                     if (count === tags.length){
                     return true;
                     }
                }
            }
        }
        return false;
    });
};
})

Upvotes: 1

Related Questions