How to use array reduce with condition in JavaScript?

wobsoriano picture wobsoriano · Jul 20, 2017 · Viewed 29.5k times · Source

So I have an array

const records = [
    {
        value: 24,
        gender: "BOYS"
    },
    {
        value: 42,
        gender: "BOYS"
    },
    {
        value: 85,
        gender: "GIRLS"
    },
    {
        value: 12,
        gender: "GIRLS"
    },
    {
        value: 10,
        gender: "BOYS"
    }
]

And I want to get the sum so I used the JavaScript array reduce function and got it right. Here is my code:

someFunction() {
  return records.reduce(function(sum, record){
    return sum + record.value; 
  }, 0);
}

With that code I get the value 173 which is correct. Now what I wanted to do is to get all the sum only to those objects who got a "BOYS" gender.

I tried something like

someFunction() {
  return records.reduce(function(sum, record){
    if(record.gender == 'BOYS') return sum + record.value; 
  }, 0);
}

But I get nothing. Am I missing something here? Any help would be much appreciated.

Answer

T4rk1n picture T4rk1n · Jul 20, 2017

When you return nothing from the reduce function it returns undefined and undefined + 1 === NaN. You should instead filter the array before reducing.

records.filter(({gender}) => gender === 'BOYS')
    .reduce((sum, record) => sum + record.value)