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.

1
  • Hi, could you please accept the most fitting answer? Commented Jan 10, 2016 at 11:19

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.