AngularJs Remove duplicate elements in ng-repeat

前端 未结 5 1019
醉话见心
醉话见心 2020-11-30 01:43

I have one dictionary which is stored in field_detail

  • {{field.displayName}}
  • 5条回答
    •  挽巷
      挽巷 (楼主)
      2020-11-30 02:29

      To piggyback off of Ben Lesh, I added the option to remove duplicate objects in an array if the keyname is falsy:

      app.filter('unique', function () {
      return function ( collection, keyname) {
          var output = [],
              keys = []
              found = [];
      
          if (!keyname) {
      
              angular.forEach(collection, function (row) {
                  var is_found = false;
                  angular.forEach(found, function (foundRow) {
      
                      if (foundRow == row) {
                          is_found = true;                            
                      }
                  });
      
                  if (is_found) { return; }
                  found.push(row);
                  output.push(row);
      
              });
          }
          else {
      
              angular.forEach(collection, function (row) {
                  var item = row[keyname];
                  if (item === null || item === undefined) return;
                  if (keys.indexOf(item) === -1) {
                      keys.push(item);
                      output.push(row);
                  }
              });
          }
      
          return output;
      };
      });
      

    提交回复
    热议问题