-1

I have an array. How can I find dublicates by type, name and size and increment amount. And after increasing amount delete the same ones.

[
    {
        "name": "Pizza with pepper",
        "imageUrl": "...",
        "type": 0,
        "size": 26,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Pizza with pepper",
        "imageUrl": "...",
        "type": 1,
        "size": 40,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Peperoni",
        "imageUrl": "...",
        "type": 0,
        "size": 30,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Peperoni",
        "imageUrl": "...",
        "type": 0,
        "size": 30,
        "price": "803",
        "amount": 1
    }
]

1 Answers1

1

const data = [
    {
        "name": "Pizza with pepper",
        "imageUrl": "...",
        "type": 0,
        "size": 26,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Pizza with pepper",
        "imageUrl": "...",
        "type": 1,
        "size": 40,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Peperoni",
        "imageUrl": "...",
        "type": 0,
        "size": 30,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Peperoni",
        "imageUrl": "...",
        "type": 0,
        "size": 30,
        "price": "803",
        "amount": 1
    }
];

const merged = data.reduce((agg, item) => {
  const key = `${item.name}-${item.type}-${item.size}`;
  if (agg[key]) {
     agg[key].amount += item.amount;
  } else {
     agg[key] = item;
  }
  return agg;
}, {});

const result = Object.values(merged);
console.log(result);
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71