-1

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.

  • Sounds like a job for [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) and here's an [example](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array). – jarmod Apr 05 '22 at 19:16
  • @jarmod but the reduce will only do the sum, so I'll need to use a combination of sort + reduce? I'll do it with big arrays, just thinking if it's the best way to do this. – Marco Vinicius Castellari Apr 05 '22 at 19:21
  • You have to do both. The selected answer below does both. It includes a clever, but arguably less than obvious, way to sort the results. – jarmod Apr 05 '22 at 22:41

2 Answers2

2

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}));
Florat
  • 119
  • 1
  • 7
2

You could take an object and get the values from it.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I'd highly recommend not reducing everything to a single statement/expression. It may be fun to write, but it really hurts readability, especially when helping someone getting familiar with the APIs / syntax of a language. – Balázs Édes Apr 05 '22 at 20:08
  • Interesting strategy for sorting the results by price. – jarmod Apr 05 '22 at 22:37