0

I have a javascript array that looks like this

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

In the above code snippet two objects has same id id:1. If id of two or more objects are same in the array. I want them to be converted into single object and the quantity property of all the object with that particular id id:1 gets accumulated. So the response array should look like this.

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

1 Answers1

2

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
  • 10,098
  • 4
  • 18
  • 39
  • 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