如何在JavaScript中使用带有条件的数组化简? [英] How to use array reduce with condition in JavaScript?
问题描述
所以我有一个数组
const records = [
{
value: 24,
gender: "BOYS"
},
{
value: 42,
gender: "BOYS"
},
{
value: 85,
gender: "GIRLS"
},
{
value: 12,
gender: "GIRLS"
},
{
value: 10,
gender: "BOYS"
}
]
我想获取 sum
,所以我使用了JavaScript数组reduce函数并正确处理了它.这是我的代码:
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);
}
使用该代码,我得到正确的值 173
.现在,我想做的就是只将所有总和归给具有"BOYS"
性别的那些对象.
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.
我尝试过类似的事情
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.
推荐答案
当您从reduce函数中不返回任何内容时,它将返回undefined和undefined + 1 === NaN.相反,您应该在缩小之前对数组进行过滤.
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)
这篇关于如何在JavaScript中使用带有条件的数组化简?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!