- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 } ]
- Related Articles
- JSON group object in JavaScript
- How to group JSON data in JavaScript?
- Group strings starting with similar number in JavaScript
- JavaScript group a JSON object by two properties and count
- Link Bootstrap List Group Items
- Convert JSON array into normal json in JavaScript
- Similar string groups in JavaScript
- How to create JSON format with group-concat in MySQL?
- JSON. stringify( ) function in JavaScript
- Regroup JSON array in JavaScript
- A group of organic compounds having similar structures and similar chemical properties in which the successive compounds differ by CH2 group is called a _________________.
- Print JSON nested object in JavaScript?
- Flattening a JSON object in JavaScript
- Sorting a JSON object in JavaScript
- MySQL query to list all the items in a group in one record?

Advertisements