Jordash
Jordash

Reputation: 3103

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

Upvotes: 0

Views: 81

Answers (3)

Johannes Jander
Johannes Jander

Reputation: 5020

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.

Upvotes: 1

Blindman67
Blindman67

Reputation: 54109

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() ];  

Upvotes: 1

Jeremy
Jeremy

Reputation: 1924

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

Upvotes: 1

Related Questions