简体   繁体   English

如何按属性值对对象数组进行排序并在该值相等时求和?

[英]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.

相关问题 如何根据一个等值的性质得到数组中各种对象的正负值之和? - How to obtain a sum of positive and negative values of various objects in an array based on a property of equal value? 如何使用 AngularJs 对对象数组中的属性值求和 - How to sum value of a property in an array of objects with AngularJs 如何按属性值数组长度对对象进行排序? - how to sort objects by property value array length? 如何基于在对象数组中共享另一个属性名称的值来对一个属性名称的值求和(在 Javascript 中) - How to sum the values of one property name based on sharing the value of another property name in an array of objects (in Javascript) 按属性值排序对象数组 - Sort Array of Objects by property value 如何在 JavaScript 的 2 个对象数组中检查相等的属性值? - How to check for equal property values in 2 Array of Objects in JavaScript? 从对象数组中提取具有另一个属性等于给定值的项目的属性值数组 - From array of objects extract array of property values for items having another property equal to given value JavaScript:按计算属性或现有属性(如果相等)对对象数组进行排序 - JavaScript: Sort array of objects by computed property or by an existing property if equal 按值对对象数组中的值求和 - Sum values in an array of objects by value 如何对数组多个对象的唯一属性的字段值求和? - How to sum values of fields for a unique property of an array multiple objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM