gpt4 book ai didi

javascript - 如果字典中的所有其他元素都相同,则对计数求和

转载 作者:行者123 更新时间:2023-12-01 00:17:26 26 4
gpt4 key购买 nike

我有一个字典数组,如下所示:

[{name:'v1', count:1}, {name:'v1', count:1}, {name:'v2', count:1}, {name:'v2', count:1}]

如果名称相同,如何将这些计数相加并形成字典,如下所示:

[{name:'v1', count:2}, {name:'v2', count:2}]

最佳答案

解决方案依赖Array.prototype.reduce , Object.entriesArray.protype.map :

const data = [{name:'v1', count:1}, {name:'v1', count:1}, {name:'v2', count:1}, {name:'v2', count:1}]

const result = Object.entries(data.reduce(
(acc, { name, count }) => {
acc[name] = count + (acc[name] || 0)
return acc
},
{}
)).map(([name, count]) => ({ name, count }))

console.log(result)

以下是将同一解决方案分为多个部分,以便于理解:

const data = [{name:'v1', count:1}, {name:'v1', count:1}, {name:'v2', count:1}, {name:'v2', count:1}]

const r1 = data.reduce(
(acc, { name, count }) => {
acc[name] = count + (acc[name] || 0)
return acc
},
{}
)
console.log(r1)

const r2 = Object.entries(r1)
console.log(r2)

const r3 = r2.map(([name, count]) => ({ name, count }))
console.log(r3)

关于javascript - 如果字典中的所有其他元素都相同,则对计数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com