-->

How to count unique results based on a particular

2019-09-06 14:55发布

问题:

I'm working with AngularJS and trying to create a filter to search properties.

I've got a select box like this:

<select 
    class="selectBox" 
    multiple="multiple" 
    ng-model="selectedSubArea" 
    ng-options="property.SubArea as (property.SubArea + ' ('+ filtered.length +')') for property in filtered = (properties | unique:'SubArea') | orderBy:'SubArea'">
</select>

This is the unique function:

myApp.filter('unique', function() {
return function(input, key) {
    var unique = {};
    var uniqueList = [];
    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;
}; });

How can I get filtered.length to work?

Here's my JSFiddle

回答1:

Here's a solution:

http://jsfiddle.net/odpw6c6q/16/

Create a filter that returns objects with count (number of times they were in the original list):

    myApp.filter('uniqueWithCount', function() {
        return function(input, key) {
            var unique = {};
            var uniqueList = [];
            var obj, val;
            for(var i = 0; i < input.length; i++){
                val = input[i][key];
                obj = unique[val];
                if (!obj) {
                    obj = unique[val] = {data: input[i], count: 0};
                    uniqueList.push(obj);
                }
                obj.count++;
            }
            return uniqueList;
        };
    });

Use that filter in your HTML:

<select class="form-control" multiple="multiple" ng-model="selectedSubArea"
ng-options="property.SubArea as (item.data.SubArea + ' ('+ item.count +')') for item in filtered = (properties | uniqueWithCount:'SubArea') | orderBy:'SubArea'"></select>