How to use array reduce with condition in JavaScript?
If the gender is 'GIRLS' it will return undefined. Add an else statement that returns sum and it should fix the problem.
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){
if(record.gender == 'BOYS') return sum + record.value;
else return sum;
}, 0);
}
console.log(someFunction())
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 should also return the sum
when the gender is GIRLS
. reduce
goes through each item and expects a return
value. If you don't return
a value, it will be undefined
. So after the third iteration, the sum
will be undefined
.
const sumBoys = records.reduce((sum, record) => {
if (record.gender.toLowerCase() === 'boys') {
return sum + record.value;
}
return sum;
}, 0);
const records = [{
value: 24,
gender: "BOYS"
}, {
value: 42,
gender: "BOYS"
}, {
value: 85,
gender: "GIRLS"
}, {
value: 12,
gender: "GIRLS"
}, {
value: 10,
gender: "BOYS"
}];
const sumBoys = records.reduce((sum, record) => {
if (record.gender.toLowerCase() === 'boys') {
return sum + record.value;
}
return sum;
}, 0);
console.log(sumBoys);
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>