Yalda Yalda - 1 year ago 87
Node.js Question

JavaScript reduce returns null if array is empty

I need the count of my objects in the array based on their type. I don't know what I'm missing here, but this is what I do:

myCounts = (myArray || []).reduce(function _countMembersByType(counts, member) {
return counts[member.type === productType.GROUP ? 'groupCount' : 'individualCount']++;
}, {groupCount: 0 , individualCount: 0});

has members,
will be
. Otherwise, it will be an object as
myCounts: {"groupCount":0,"individualCount":0}
as I would expect.

I'm new to JS and would appreciate any help!

Answer Source

Your returning the result of plus 1'ing, so in the next iteration, previous or counts will be a number not your base object.

You need to return the whole object.

myCounts = (myArray || []).reduce(function _countMembersByType(counts, member) {
  counts[member.type === productType.GROUP ? 'groupCount' : 'individualCount']++;
  return counts;
}, {
  groupCount: 0,
  individualCount: 0