[
{
"id": 1,
"price": 100
},
{
"id": 1,
"price": 80
},
{
"id": 2,
"price": 8
},
{
"id": 1,
"price": 85
}
]
[
{
"id": 1,
"price": 88.33 // AVERAGE VALUE BETWEEN DUPLICATED OBJECTS
},
{
"id": 2,
"price": 8
}
]
我正在合并并获取 重复对象的平均价格 。
我尝试使用filter()
函数,但是我删除了重复项而不合并价格。
答案 0 :(得分:1)
您可以将.reduce()
与ES6 Map一起使用。通过使用reduce()
,您可以将所有对象累积到Map中,其中键是对象中的id
,并且值是给定{{1} }。然后,您可以使用Array.from()
将price
转换回数组,在其中您可以提供映射功能,以将id
对从映射转换为对象。对象的Map
键将是[key, value]
数组(price
)中所有数字的总和除以数组的长度,这将为您提供平均值。
请参见以下示例:
value
答案 1 :(得分:1)
如果要避免多余的循环和多余的属性不是问题,可以为每个对象使用吸气剂,如下所示:
您可以使用函数Array.prototype.reduce
通过id
对对象进行分组,并使用函数Object.values
来提取分组的值。
访问该属性时,getter price
计算平均值。
其他属性:
{
count: Integer // count of repeated ids.
sum: Double // total sum of prices
}
const arr = [ { "id": 1, "price": 100 }, { "id": 1, "price": 80 }, { "id": 2, "price": 8 }, { "id": 1, "price": 85 } ],
result = Object.values(arr.reduce((r, {id, price}) => {
let current = (r[id] || (r[id] = {id, sum: 0, count: 0, get price() {
return this.sum / this.count;
}}));
current.sum += price;
current.count++;
return r;
}, {}));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
使用forEach
循环并使用键为id
和总价来构建对象。
使用上述对象的Object.values
并计算平均值。
const data = [
{
id: 1,
price: 100,
},
{
id: 1,
price: 80,
},
{
id: 2,
price: 8,
},
{
id: 1,
price: 85,
},
];
const process = (arr) => {
const res = {};
arr.forEach(({ id, price }) => {
res[id] ??= { id, sum: 0, count: 0 };
res[id].sum += price;
res[id].count += 1;
});
return Object.values(res).map(({ id, sum, count }) => ({
id,
price: sum / count,
}));
};
console.log(process(data));