How To Use Array Reduce With Condition In Javascript?
Solution 1:
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)
Solution 2:
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"
}
];
functionsomeFunction() {
return records.reduce(function(sum, record) {
return (record.gender !== 'BOYS') ? sum : sum + record.value;
}, 0);
}
console.log(someFunction());
</script>
Solution 3:
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"
}
]
functionsomeFunction() {
return records.reduce(function(sum, record){
if(record.gender == 'BOYS') return sum + record.value;
elsereturn sum;
}, 0);
}
console.log(someFunction())
Solution 4:
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') {
returnsum + record.value;
}
returnsum;
}, 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);
Solution 5:
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') {
returnsum + record.value;
} else{
returnsum
};
}, 0);
Post a Comment for "How To Use Array Reduce With Condition In Javascript?"