简体   繁体   English

如何过滤出对象数组的重复项

[英]How to filter out Duplicates of an array of objects

I have an array of objects which look like this: 我有一个看起来像这样的对象数组:

$scope.SACCodes = [
    {'code':'023', 'description':'Spread FTGs', 'group':'footings'},
    {'code':'024', 'description':'Mat FTGs', 'group':'footings'},
    {'code':'025', 'description':'CONT. FTGs', 'group':'footings'},
    {'code':'025', 'description':'CONT. FTGs', 'group':'levels'},
    {'code':'023', 'description':'Trucks', 'group':'footings'}
]

I need to filter out duplicates where the code and the group are duplicates. 我需要过滤掉重复的codegroup重复的地方。 If only one of them is the same it shouldn't filter it out. 如果其中只有一个相同,则不应将其过滤掉。

This uses a helper hash to note which combination of code and group have already been processed. 这使用帮助程序哈希值来记录已处理的codegroup组合。 Only if it finds a hitherto unused combination does it add it to the retVal array; 仅当找到迄今为止未使用的组合时,才会将其添加到retVal数组中;

function dedup() {
    var dups = {};
    var retVal = [];

    for (var i = 0; i < $scope.SACCodes.length; i++) {
       var sCode = $scope.SACCodes[i];
       var key = sCode.code +'/'+ sCode.group;
       if (!dups[key]) {
          retVal.push (sCode);
          dups[key] = sCode;
       }
    }
    return retVal;
}

See working example 参见工作示例

Couple of years down the road you could use Object.values(dups); 几年后,您可以使用Object.values(dups); instead of retVal and thereby shorten the code. 而不是retVal ,从而缩短了代码。

Here is another approach based on TLindig's answer to a similar question . 这是基于TLindig对类似问题的回答的另一种方法。

Add a filter method to the scope: 向范围添加过滤方法:

$scope.onlyUnique = function(value, index, self) { 
  codes = self.map(function(c) {return c.code});
  groups = self.map(function(c) {return c.group});
  return codes.indexOf(value.code) === index || groups.indexOf(value.group) === index;

Call the filter method in your ng-repeat or wherever you want the unique values: 在ng-repeat或任何需要唯一值的地方调用filter方法:

<div ng-repeat="c in SACCodes.filter(onlyUnique)">code: {{c.code}} desc: {{c.description}} group: {{c.group}}</div>

Output: 输出:

code: 023 desc: Spread FTGs group: footings
code: 024 desc: Mat FTGs group: footings
code: 025 desc: CONT. FTGs group: footings
code: 025 desc: CONT. FTGs group: levels

The ES6 way. ES6方式。

var m = new Map();

SACCodes.forEach ( function( item ) {
    var key = item.code + item.group;
    if ( !m.has( key ) ){
        m.set( key, item );
    }
});
SACCodes= [ ...m.values() ];  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM