How to use array reduce with condition in JavaScript? How to use array reduce with condition in JavaScript? vue.js vue.js

How to use array reduce with condition in JavaScript?


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)


You need to return the current sum and not undefined if your condition is not matched.

Otherwise you aren't returning your accumulator to the reduce function and end up adding unefined + record.value when matched or undefined + undefined when it is not matched.

Try this:

<script>  const records = [{      value: 24,      gender: "BOYS"    },    {      value: 42,      gender: "BOYS"    },    {      value: 85,      gender: "GIRLS"    },    {      value: 12,      gender: "GIRLS"    },    {      value: 10,      gender: "BOYS"    }  ];  function someFunction() {    return records.reduce(function(sum, record) {     return (record.gender !== 'BOYS') ? sum : sum + record.value;    }, 0);  }  console.log(someFunction());</script>