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
  • 71,416
  • 24
  • 140
  • 167

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,567
  • 3
  • 17
  • 40
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 Barot
  • 2,671
  • 2
  • 17
  • 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.
  • 35,491
  • 6
  • 51
  • 50
0

You can use underscore:

var newObj = _.uniq(market, function(p){ return p.group_id; });
Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44