
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Group Similar Items in JSON in JavaScript
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 } ]
Advertisements