[英]How to sort an array of objects by property values and sum when this value is equal?
I have an array of objects like this:我有一组这样的对象:
var values = [
{
"price": 10,
"amount": 2
}, {
"price": 10,
"amount": 2
}, {
"price": 5,
"amount": 3
}, {
"price": 15,
"amount": 5
}
];
How can I sort it by the "price" value and when the "price" is the same I sum the "amount" value, so it will result like this:我如何按“价格”值对其进行排序,当“价格”相同时,我将“金额”值相加,结果将如下所示:
var values = [
{
"price": 5,
"amount": 3
}, {
"price": 10,
"amount": 4
}, {
"price": 15,
"amount": 5
}
];
I can sort it by using:我可以使用以下方法对其进行排序:
values.sort((a, b) => a.price - b.price);
But I don't know how to sum the amount when the price is equal.但是我不知道在价格相等的情况下如何求和。
Probably not most effective but most expressive:可能不是最有效但最具表现力的:
[...new Set(values.map(({price}) => price))]
.sort((a, b) => a - b)
.map((p) => values
.filter(({price}) => p === price)
.reduce((t, e) => {
t.amount += e.amount;
return t;
}, {price: p, amount: 0}));
You could take an object and get the values from it.您可以使用 object 并从中获取值。
const values = [{ price: 10, amount: 2 }, { price: 10, amount: 2 }, { price: 5, amount: 3 }, { price: 15, amount: 5 }], grouped = Object.values(values.reduce((r, { price, amount }) => { r[price]??= { price, amount: 0 }; r[price].amount += amount; return r; }, {})); console.log(grouped);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.