如何修复这个函数,根据它们的出现次数来计算项目?

huangapple go评论76阅读模式
英文:

How to fix this function that counts items based on their occurrence?

问题

我有以下的数组:

const sales = [
  { name: 'a', count: 0 },
  { name: 'a', count: 0 },
  { name: 'b', count: 0 }
]

我想要统计它们的出现次数:

const result = []
sales.forEach(sale => {
  if (result.includes(sale)) { // 检查项目是否在新数组中
    sale.count += 1 // 如果是,将计数加一
  } else {
    result.push(sale) // 如果不是,将项目放入数组中
  }
})

但是if语句永远不会返回true。为什么会这样,以及如何修复它?

英文:

I have the following array:

const sales = [
  { name: 'a', count: 0 },
  { name: 'a', count: 0 },
  { name: 'b', count: 0 }
]

I want to count their occurrence:

const result = []
sales.forEach(sale => {
  if (result.includes(sale)) { // check if the item is in the new array
    sale.count += 1 // if it is, add one to count
  } else {
    result.push(sale) // if not, put the item in the array 
  }
})

But the if statement never returns true. Why is this and how to fix it?

答案1

得分: 1

在https://stackoverflow.com/a/201471/2358409上已经有一个很好的答案,解释了为什么你的解决方案不起作用。

要使其起作用,你可以将array中的每个objects转换为string,并使用Set来计算不同元素的数量。

const sales = [
  { name: 'a', count: 0 },
  { name: 'a', count: 0 },
  { name: 'b', count: 0 }
]

const count = new Set(sales.map(s => JSON.stringify(s))).size;
console.log(count)
英文:

There exists a good answer already at https://stackoverflow.com/a/201471/2358409 that explains why your solution doesn't work.

To make it work, you could transform individual objects in the array to string, and use a Set to count distinct elements.

const sales = [
  { name: 'a', count: 0 },
  { name: 'a', count: 0 },
  { name: 'b', count: 0 }
]

const count = new Set(sales.map(s => JSON.stringify(s))).size;
console.log(count)

huangapple
  • 本文由 发表于 2020年1月3日 14:16:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定