Group Similar Items in JSON in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented ProgrammingJSON

Suppose, we have a JSON Array that contains data about some tickets like this −

const arr = [
   {
      "quantity": "1",
      "description": "VIP Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "VIP Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "VIP Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "Regular Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "Regular Ticket to Event"
   },
];

We are required to write a JavaScript function that takes in one such array. The function should group similar objects together and sum up their quantity property.

Two objects will be considered if they have identical values for the "description" property.

Example

The code for this will be −

const arr = [
   {
      "quantity": "1",
      "description": "VIP Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "VIP Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "VIP Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "Regular Ticket to Event"
   },
   {
      "quantity": "1",
      "description": "Regular Ticket to Event"
   },
];
const groupAndAdd = arr => {
   const res = [];
   arr.forEach(el => {
      if (!this[el.description]) {
         this[el.description] = {
            description: el.description, quantity: 0
         };
         res.push(this[el.description]);
      };
      this[el.description].quantity += +el.quantity;
   }, {});
   return res;
}
console.log(groupAndAdd(arr));

Output

And the output in the console will be −

[
   { description: 'VIP Ticket to Event', quantity: 3 },
   { description: 'Regular Ticket to Event', quantity: 2 }
]
raja
Published on 21-Nov-2020 14:32:03
Advertisements