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?
Example 1: Perform Intersection Using SetThe for...of loop is used to iterate over the second Set elements. The has() method is used to check if the element is in the first Set . If the element is present in the first Set , that element is added to the intersectionResult array using the push() method.
Firstly, sort both the arrays. Then, Keep a pointer for each of the two arrays. If both elements that are being pointed are equal, then it is a common element. Otherwise, increment the pointer of the array with a lower value of the current element.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With