How to make ng-repeat filter out duplicate results

前端 未结 16 2921
鱼传尺愫
鱼传尺愫 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:13

    This might be overkill, but it works for me.

    Array.prototype.contains = function (item, prop) {
    var arr = this.valueOf();
    if (prop == undefined || prop == null) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == item) {
                return true;
            }
        }
    }
    else {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i][prop] == item) return true;
        }
    }
    return false;
    }
    
    Array.prototype.distinct = function (prop) {
       var arr = this.valueOf();
       var ret = [];
       for (var i = 0; i < arr.length; i++) {
           if (!ret.contains(arr[i][prop], prop)) {
               ret.push(arr[i]);
           }
       }
       arr = [];
       arr = ret;
       return arr;
    }
    

    The distinct function depends on the contains function defined above. It can be called as array.distinct(prop); where prop is the property you want to be distinct.

    So you could just say $scope.places.distinct("category");

提交回复
热议问题