繁体   English   中英

Javascript数组减少返回零而不是未定义

[英]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秒,类似地,不同日期范围不会返回3秒。

问题是,如果你从不接触数组的元素,那么它就会作为数组中的一个洞,这意味着它被视为未定义。 因为你知道数组的长度,所以我只会用零预填充数组。 任何发生的情绪分数都会增加。 任何没有的将保持其初始值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM