Showing 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 relate 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 in the lines:

<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 () function? Is there a better way to achieve the same goal?

+4
source share
1 answer

You can just use an array of features .filterand .indexOfinside the filter:

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

And then for HTML it looks like this:

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

http://jsfiddle.net/8u4Zg/

+9
source

All Articles