0

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});

When myArray has members, myCounts will be null. 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!

1
  • 1
    You mean When myArray does NOT have members Commented Jun 10, 2016 at 13:00

1 Answer 1

2

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
});

fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see! Dumb mistake! Thanks :)

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.