0

I have a javascript array like this

var array = [{
        id: 1,
        quantity: 2
    },
    {
        id: 2,
        quantity: 1
    },
    {
        id: 1,
        quantity: 5
    }
]

how to convert this array into

var resArray = [{
        id: 1,
        quantity: 7
    },
    {
        id: 2,
        quantity: 1
    }
]

where each id property of object is unique and all quantity property(with same id) gets added.

Jason Roman
  • 7,836
  • 10
  • 33
  • 37

1 Answers1

1

Using Array.reduce, you can group the array by id key value and can sum the quantities of same id.

const array = [{
    id: 1,
    quantity: 2
  },
  {
    id: 2,
    quantity: 1
  },
  {
    id: 1,
    quantity: 5
  }
];

const reducedArr = array.reduce((acc, cur) => {
  acc[cur.id] ? acc[cur.id].quantity += cur.quantity : acc[cur.id] = cur;
  return acc;
}, {});

const output = Object.values(reducedArr);
console.log(output);
Derek Wang
  • 9,720
  • 4
  • 15
  • 38
  • thanks a lot. well that's perfect. though i was wondering if there is anyway possible to directly recuce the array into result array(acc being an empty array instead of empty object). – kazi nur hossain tipu Oct 21 '20 at 11:17