0

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. If only one of them is the same it shouldn't filter it out.

Jordash
  • 2,926
  • 8
  • 38
  • 77

3 Answers3

1

This uses a helper hash to note which combination of code and group have already been processed. Only if it finds a hitherto unused combination does it add it to the retVal array;

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); instead of retVal and thereby shorten the code.

Johannes Jander
  • 4,974
  • 2
  • 31
  • 46
1

Here is another approach based on TLindig's answer to a similar question.

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:

<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
Community
  • 1
  • 1
Jeremy
  • 1,824
  • 14
  • 20
1

The ES6 way.

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() ];  
Blindman67
  • 51,134
  • 11
  • 73
  • 136