英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论