Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  128] [ 7]  / answers: 1 / hits: 60987  / 7 Years ago, thu, july 20, 2017, 12:00:00

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.


More From » arrays

 Answers
87

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)

[#57026] Monday, July 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bruno

Total Points: 602
Total Questions: 100
Total Answers: 111

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;