【发布时间】:2020-05-30 09:31:54
【问题描述】:
我有一个示例数组,我试图通过键的出现次数来减少它(本示例中的情绪):
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)。返回的数据将基于日期范围。因此,在某些情况下,可能不会返回 1s,类似地,其他日期范围也不会返回 3s。
【问题讨论】:
-
是否有最大情绪值?想知道你是否可以用全零预填充数组。
-
介于 0 和 3 之间 - 所以只有 4 个选项 - UI 将这些表示为笑脸 :)
-
除了预先用零填充数组(因为您事先知道它的长度),使用对象作为哈希是否有问题?
-
我想避免
object,因为我在 Vue.js 的v-for循环中使用结果
标签: javascript arrays ecmascript-6 reduce