Search code examples
javascriptjsonangularjsfilterunique

Angular unique filter for nested ng-repeat


I wanted to insert the content so that it prints each students location next to a checkbox without having any duplicated locations. My HTML looks like this:

<ul ng-repeat="group in groups">
  <li ng-repeat="student in group.students | unique : 'location'">
     <input type="checkbox" id="location">
     <label for="location" ng-repeat="loc in student.location | unique : 'loc'">{{loc}}</label>
  </li>
</ul>

I am using this filter code to filter out repeated items in my JSON file.

App.js

app.filter('unique', function() {
    return function(input, key) {
        var uniqueList = [];
        var unique = {};
        for(var i = 0; i < input.length; i++) {
            if(typeof unique[input[i][key]] == "undefined") {
                unique[input[i][key]] = "";
                uniqueList.push(input[i]);

            }
        }
        return uniqueList;
    };
});

My JSON files is formatted like this :

"groups" : [
    {
        "name": "a",
        "students" : [
            {
                "student_name" : "Nate",
                "location" : "California"
            },
            {
                "student_name" : "Natalie",
                "location": "Michigan"
            },
            {
                "student_name" : "Tim",
                "location" : "California"
            }
        ]
    },
    {
        "name" : "b",
        "students" : [
            {
                "student_name" : "Brian",
                "location" : "California"
            }
        ]
    }
]

It prints California Michigan California. I assume this is because the uniqueList resets when it enters another group. I am unsure how to go about this with nested objects. Can someone explain to me what I am doing wrong?


Solution

  • You won't be able to do this in a filter since you are correct each group resets it. You will need to have something combine the groups before hand and then loop through the combined group.