How to use array reduce with condition in JavaScript?

Viewed 51101

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.

9 Answers

Well, in case you just want to stick with reduce and don't want to use filter, you can do it this way:

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

  var res = records.reduce(function(sum, record){
    if(record.gender === 'BOYS') {
       return sum + record.value;
     } else{
        return sum
    }; 
  }, 0);
  console.log(res);

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

We can use this simplified code

let res= records.reduce(function(a,b){ 
    return (b.gender === "BOYS" && (a+parseInt(b.value))) || a; 
}, 0);

you got an error because, reduce method iterate.in each element i. array and returns the.accumulated value,

what happen is, when your condition did not meet, the value of accumulator becomes.undefined because you.did not return it.

you need to sum first if it meets the.condition. and outside the if scope return the sum,

Assuming that if records was empty you want to set an accumulator value that matches your output. Also the definition of empty when records.length === 0 vs when only count of BOYS is 0 might be different.

const defaultValue = 0, target = 'BOYS'
const result = records.reduce( (sum,{gender,value})=>{
   return gender === target ? (sum||0)+value : sum;
},defaultValue);

some fun with reduce and your question: https://jsfiddle.net/gillyspy/021axnsr/8/

Related