How to make ng-repeat filter out duplicate results

前端 未结 16 2937
鱼传尺愫
鱼传尺愫 2020-11-22 06:52

I\'m running a simple ng-repeat over a JSON file and want to get category names. There are about 100 objects, each belonging to a category - but there are only

16条回答
  •  耶瑟儿~
    2020-11-22 07:10

    I had an array of strings, not objects and i used this approach:

    ng-repeat="name in names | unique"
    

    with this filter:

    angular.module('app').filter('unique', unique);
    function unique(){
    return function(arry){
            Array.prototype.getUnique = function(){
            var u = {}, a = [];
            for(var i = 0, l = this.length; i < l; ++i){
               if(u.hasOwnProperty(this[i])) {
                  continue;
               }
               a.push(this[i]);
               u[this[i]] = 1;
            }
            return a;
        };
        if(arry === undefined || arry.length === 0){
              return '';
        }
        else {
             return arry.getUnique(); 
        }
    
      };
    }
    

提交回复
热议问题