首页 > 解决方案 > 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)。返回的数据将基于日期范围。因此,可能会有没有1s 返回的情况,同样地3,不同日期范围也没有返回 s。

标签: javascriptarraysecmascript-6reduce

解决方案


问题是,如果您从未接触过数组中的某个元素,那么它就会在数组中保留为一个洞,这意味着它被视为未定义。由于您知道数组的长度,因此我只需用零预填充数组。任何确实发生的情绪分数都将增加。任何不这样做的人都将保持其初始值。

return sentiments.reduce((hash, { sentiment }) => {
  hash[sentiment] = hash[sentiment] + 1
  return hash
}, [0, 0, 0, 0])

推荐阅读