0
var availableMarketGroups = {};

angular.forEach(function (market) {

  if (availableMarketGroups[market.group_id]) { // market.group_id is not sorted id
       availableMarketGroups[market.group_id].count++;
  }  
});

market.group_id - number ,not sorted, and sometimes its duplicates availableMarketGroups[market.group_id].count - its length

Lets see the image for more info.

The numbers of the market groups don't represent real amount of markets.

availableMarketGroups[market.group_id].count show - 15 ,but in real it should be 5 (5 groups) ,because market.group_id is duplicates.

enter image description here

How can i ignore duplicated market.group_id values in if statement ?

AT82
  • 67,510
  • 23
  • 129
  • 159

4 Answers4

0
var availableMarketGroups = {};
var groupsProcessed = [];

angular.forEach(availableMarketGroups, function(marketGroup) {
    if (groupsProcessed.indexOf(marketGroup.group_id) < 0) {
        groupsProcessed.push(marketGroup.group_id);
        availableMarketGroups[market.group_id].count++;
    }
});
Kyle Richardson
  • 5,331
  • 2
  • 16
  • 39
0

Answer for counting unique array elements is to make a function as given below.

var counts = {};
for (var i = 0; i < arr.length; i++) {
    counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}

It will return the unique counts of elements in the array.

Reference : Count unique elements in array without sorting

Community
  • 1
  • 1
Tirthraj Rao
  • 2,631
  • 2
  • 16
  • 33
0

Hard to say without your data. Generally speaking, you should be able to reduce this down to the unique Set of group_ids:

const uniqueGroups = markets.reduce(function(set, market) {
  if (!set.has(market.group_id)) {
    set.add(market.group_id);
  }
  return set;
}, new Set());

console.log('Unique group count: ', uniqueGroups.size);
Rob M.
  • 33,381
  • 6
  • 50
  • 46
0

You can use underscore:

var newObj = _.uniq(market, function(p){ return p.group_id; });
Emad Dehnavi
  • 2,891
  • 4
  • 16
  • 42