0

I would like to merge similar objects and combine the quantity.

My array:

result = [
{itemNumber:'1288',quantity:700},
{itemNumber:'3298',quantity:1000},
{itemNumber:'1288',quantity:300}
]

What I did:

 result = result.reduce((sum, val) => {
      for (let i in sum) {
          if (sum[i].itemNumber === val.itemNumber) {
              return sum 
          }
      }
      sum.push(val);
      return sum;
  }, []);

My expected result:

result = [
    {itemNumber:'1288',quantity:1000},
    {itemNumber:'3298',quantity:1000},
    ]

If there is a way to do it with lodash I would like to know because I could not find one.

Thanks for your help.

Bar Levin
  • 89
  • 8

2 Answers2

0

You can store totals in an object and convert them back to an array. However, in this approach you should notice that the order of elements might change.

const input = [
  {itemNumber:'1288',quantity:700},
  {itemNumber:'3298',quantity:1000},
  {itemNumber:'1288',quantity:300}
];

// stores itemNumber, totalQuantity pairs.
// Example: {'1288': 1000, '3298': 1000} 
const totals = input.reduce((acc, val) => {
  const key = val.itemNumber;
  const { quantity } = val;
  const totalSoFar = acc[key] || 0;
  return {...acc, [key]: totalSoFar + quantity};
}, {});

const result = Object.entries(totals)
  .map(([itemNumber, quantity]) => ({itemNumber, quantity}));
console.log(result);
Onur Arı
  • 502
  • 1
  • 4
  • 16
0

You can try this, it's a similar in relation of your code

result = [
{itemNumber:'1288',quantity:700},
{itemNumber:'3298',quantity:1000},
{itemNumber:'1288',quantity:300}
];

let rt = Object.values(result.reduce((acc, v) => {
   if (!acc[v.itemNumber]) {
       acc[v.itemNumber] = {id: v.itemNumber, quantity: 0};
   }
   acc[v.itemNumber].quantity += v.quantity;
   return acc;
}, {}));




console.log(rt);
jradelmo
  • 116
  • 1
  • 9