【发布时间】:2022-06-14 17:54:16
【问题描述】:
我想使用reduce返回新数组。例如,
const product = [
{ color: 'orange', type: 'hat', count: 1 },
{ color: 'orange', type: 'hat', count: 1 },
{ color: 'orange', type: 'shoes', count: 1 },
{ color: 'blue', type: 'food', count: 1 },
];
产品列表需要像下面这样,因为有两个“帽子”,因此计数应该是 2,并且应该删除一个 { color: 'orange', type: 'hat', count: 1 }。
const result = product.reduce((acc, curr) => {
// I want to make new array like
// const product = [
// { color: 'orange', type: 'hat', count: 2 },
// { color: 'orange', type: 'shoes', count: 1 },
// { color: 'blue', type: 'food', count: 1 },
//];
return acc
}
谢谢!
【问题讨论】:
-
该任务也可以描述为分组、合并和聚合。这是一项非常常见的任务,可以通过通用实现但可自定义的减速器功能来解决...见..."How to group and merge array entries and to sum-up values on multiple common (but not all) keys?"stackoverflow.com/questions/72411474/…
标签: javascript arrays find lookup reduce