javascript - Javascript数组减少返回零而不是未定义
问题描述
我有一个示例数组,我试图通过键的出现次数来减少它(本例中的情绪):
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
}, [])
}
它几乎就在那里。我想不通的是undefined
当没有情绪分数时如何替换0
(这是可能的)。
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])
推荐阅读
- java - 如何将 ScrollView 添加到导航抽屉
- javascript - Selenium Webdriver 错误 [UnhandledPromiseRejectionWarning]
- javascript - browser.alarms 未使用 webextension-polyfill 定义
- visual-studio-code - 有没有办法改变VScode中评论的背景颜色?
- javascript - Javascript验证不起作用,但PHP验证有效
- react-native - 如何在本机反应中使孩子在主要方向上对齐?
- uwp - UWP 键盘加速器的功能
- ios - libc++abi.dylib segue 错误,带有 NSException 类型的未捕获异常
- c++ - 创建一个简单的前向迭代器,它自动在循环缓冲区的“结束”处换行
- java - 重用 ActionListener