Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying intersection of two arrays in angular js

Tags:

angularjs

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?

like image 880
user3852791 Avatar asked Jul 28 '14 16:07

user3852791


People also ask

How do you use intersection in Javascript?

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.

How do you print common elements in two arrays in Javascript?

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.


1 Answers

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/

like image 159
dave Avatar answered Oct 09 '22 13:10

dave