Javascript 数组减少 return 零而不是未定义
Javascript array reduce return zero instead of undefined
我有一个示例数组,我正在尝试减少键的出现次数(本例中为情绪):
const sentimentLog = [
{
id: 1,
createdOn: new Date('2020-02-13'),
sentiment: 1
},
{
id: 2,
createdOn: new Date('2020-02-12'),
sentiment: 1
},
{
id: 3,
createdOn: new Date('2020-02-12'),
sentiment: 2
},
{
id: 4,
createdOn: new Date('2020-02-11'),
sentiment: 3
},
{
id: 5,
createdOn: new Date('2020-02-11'),
sentiment: 2
},
{
id: 6,
createdOn: new Date('2020-02-10'),
sentiment: 1
},
{
id: 7,
createdOn: new Date('2020-02-10'),
sentiment: 2
},
{
id: 8,
createdOn: new Date('2020-02-09'),
sentiment: 1
}
]
我正在使用:
const sentimentGrouped = (sentiments) => {
return sentiments.reduce((hash, { sentiment }) => {
hash[sentiment] = (hash[sentiment] || 0) + 1
return hash
}, [])
}
快到了。我想不通的是如何在没有 0
的情绪分数(有可能)时替换 undefined
。
console.log('sentimentGrouped', sentimentGrouped(sentimentLog))
以上产生:
"sentimentGrouped" [undefined, 4, 3, 1]
而我想要:
"sentimentGrouped" [0, 4, 3, 1]
我错过了什么?
提前致谢。
编辑:我会进一步详细说明,将返回 4 个分数(0 到 3)。返回的数据将基于日期范围。因此,在某些情况下,可能不会返回 1
s,类似地,不同日期范围也不会返回 3
s。
问题是,如果您从未接触过数组的元素,那么它就会作为数组中的一个空洞存在,这意味着它会被视为未定义。因为你知道数组的长度,所以我会用零预填充数组。确实发生的任何情绪分数都会增加。任何没有的将保持其初始值。
return sentiments.reduce((hash, { sentiment }) => {
hash[sentiment] = hash[sentiment] + 1
return hash
}, [0, 0, 0, 0])
我有一个示例数组,我正在尝试减少键的出现次数(本例中为情绪):
const sentimentLog = [
{
id: 1,
createdOn: new Date('2020-02-13'),
sentiment: 1
},
{
id: 2,
createdOn: new Date('2020-02-12'),
sentiment: 1
},
{
id: 3,
createdOn: new Date('2020-02-12'),
sentiment: 2
},
{
id: 4,
createdOn: new Date('2020-02-11'),
sentiment: 3
},
{
id: 5,
createdOn: new Date('2020-02-11'),
sentiment: 2
},
{
id: 6,
createdOn: new Date('2020-02-10'),
sentiment: 1
},
{
id: 7,
createdOn: new Date('2020-02-10'),
sentiment: 2
},
{
id: 8,
createdOn: new Date('2020-02-09'),
sentiment: 1
}
]
我正在使用:
const sentimentGrouped = (sentiments) => {
return sentiments.reduce((hash, { sentiment }) => {
hash[sentiment] = (hash[sentiment] || 0) + 1
return hash
}, [])
}
快到了。我想不通的是如何在没有 0
的情绪分数(有可能)时替换 undefined
。
console.log('sentimentGrouped', sentimentGrouped(sentimentLog))
以上产生:
"sentimentGrouped" [undefined, 4, 3, 1]
而我想要:
"sentimentGrouped" [0, 4, 3, 1]
我错过了什么?
提前致谢。
编辑:我会进一步详细说明,将返回 4 个分数(0 到 3)。返回的数据将基于日期范围。因此,在某些情况下,可能不会返回 1
s,类似地,不同日期范围也不会返回 3
s。
问题是,如果您从未接触过数组的元素,那么它就会作为数组中的一个空洞存在,这意味着它会被视为未定义。因为你知道数组的长度,所以我会用零预填充数组。确实发生的任何情绪分数都会增加。任何没有的将保持其初始值。
return sentiments.reduce((hash, { sentiment }) => {
hash[sentiment] = hash[sentiment] + 1
return hash
}, [0, 0, 0, 0])