user3852791
user3852791

Reputation: 327

Displaying intersection of two arrays in angular js

In angular I have two lists in $scope. One is a list of packages, and the second is a list of tags that apply to them. Consider for example:

$scope.packages = [ { 
                      name = "pkg1",
                      tags = [ 1, 3]
                    }, {
                      name = "pkg2",
                      tags = [ 2, 3]
                    }]
$scope.tags = [ { 
                  id = 1,
                  name = "tag1"
                }, {
                  id = 2,
                  name = "tag2"
                }, {
                  id = 3,
                  name = "tag3"
                }]

I want to display this using something along the lines of:

<ul>
   <li ng-repeat = "pkg in packages">
      {{pkg.name}}
      <ul>
          <li ng-repeat = "tag in tags | filter : intersect(pkg.tags)">
              {{tag.name}}
          </li>
      </ul>
   </li>
</ul>

How can I get the filter: intersect() functionality? Is there a better way of achieving the same end?

Upvotes: 5

Views: 9106

Answers (1)

dave
dave

Reputation: 64657

You could just use the .filter and .indexOf array functions inside of a filter:

angular.module('myApp',[]).filter('intersect', function(){
    return function(arr1, arr2){
        return arr1.filter(function(n) {
                   return arr2.indexOf(n) != -1
               });
    };
});

And then for the HTML it looks like this:

<li ng-repeat="tag in tags | intersect: pkg.tags">

http://jsfiddle.net/8u4Zg/

Upvotes: 10

Related Questions