suman
suman

Reputation: 195

Counting and storing distinct elements and their counts from an array of object

I have an array of object and I want to count the number of distinct elements and counts of those objects.

[ { name: 'Suman',
    game: '5A'
  },
  { name: 'Suman',
    game: '5A'
  },
  { name: 'Namus',
    game: '5A'
  },
  { name: 'Namus',
    game: '5A'
  }
]

I want to count the number of distinct names and store them in an object. I have tried it by 1# pushing all the names in an array, 2# then sorting them, 3# then calculating the number of distinct names and 4# finally pushing them to the object. This process is too long. Is there a shorter way to do this. I am using Nodejs

Thanks in advance

Upvotes: 0

Views: 194

Answers (2)

Mike S
Mike S

Reputation: 42345

This is a great place to use the reduce function:

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

...

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

It would look something like this:

var arr = [ { name: 'Suman',
    game: '5A'
  },
  { name: 'Suman',
    game: '5A'
  },
  { name: 'Namus',
    game: '5A'
  },
  { name: 'Namus',
    game: '5A'
  }
]

var counts = arr.reduce(function(counts, item) {
    counts[item.name] = (counts[item.name] || 0) + 1;
    return counts;
}, {});

counts is then:

{ Suman: 2, Namus: 2 }

Asked in the comments:

what if i want the count as well as name in an array of object like [{name: 'Suman', count:'2'}, {name:'Namus', count:'2'}]

If you already have counts from the reduce call above, then you can map its keys to the format you want:

var countsArray = Object.keys(counts).map(function(name) {
    return {name: name, count: counts[name]};
});

countsArray is then:

[ { name: 'Suman', count: 2 },
  { name: 'Namus', count: 2 } ]

Upvotes: 0

Rubens Pinheiro
Rubens Pinheiro

Reputation: 499

You will create a new object, where the key is the name and the value the count:

var youArr = [ 
  { name: 'Suman',
    game: '5A'
  },
  { name: 'Suman',
    game: '5A'
  },
  { name: 'Namus',
    game: '5A'
  },
  { name: 'Namus',
    game: '5A'
  }
];

var count = {}
for(var i=0; i < youArr.length; i++){
    count[youArr[i].name] = count[youArr[i].name] || 0;
    count[youArr[i].name]++;
}

alert(count['Namus']); // 2

Upvotes: 2

Related Questions