Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Group a JSON Object by Two Properties and Count
When working with JSON data, you often need to group objects by multiple properties and count occurrences. This is useful for data analysis, creating summaries, or generating reports from complex datasets.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format for transferring data between systems. It uses key-value pairs where keys are strings and values can be various data types. Each entry is separated by commas, for example: {"name": "Peter", "age": 25}.
const jsonData = [
{ name: 'Aaron', year: 2020, month: 'May' },
{ name: 'Peter', year: 2021, month: 'December' },
{ name: 'Jack', year: 2021, month: 'March' }
]
Algorithm for Grouping and Counting
To group JSON objects by two properties and count occurrences, follow these steps:
Step 1: Define your JSON data array
Step 2: Create a function that takes the array and two property names
Step 3: Initialize an empty object to store grouped results
Step 4: Iterate through each object in the array
Step 5: Combine the two property values with an underscore as a key
Step 6: Count occurrences: increment if key exists, otherwise set to 1
Step 7: Return the grouped result object
Example: Grouping by Location and Identity
// Sample JSON data with location and identity properties
const jsonData = [
{"location": "Kerala", "identity": "Employee"},
{"location": "Kerala", "identity": "Visitor"},
{"location": "Kerala", "identity": "Visitor"},
{"location": "Kerala", "identity": "Worker"},
{"location": "Mumbai", "identity": "Employee"},
{"location": "Mumbai", "identity": "Resident"},
{"location": "Mumbai", "identity": "Worker"},
{"location": "Mumbai", "identity": "Resident"},
{"location": "Hyderabad", "identity": "Resident"},
{"location": "Hyderabad", "identity": "Homemaker"},
{"location": "Hyderabad", "identity": "Employee"},
{"location": "Hyderabad", "identity": "Resident"},
{"location": "Hyderabad", "identity": "Homemaker"},
{"location": "Hyderabad", "identity": "Resident"}
];
// Function to group by two properties and count occurrences
function groupAndCount(array, property1, property2) {
const grouped = {};
// Iterate through each object in the array
for (let i = 0; i
Grouped data with counts:
{
Kerala_Employee: 1,
Kerala_Visitor: 2,
Kerala_Worker: 1,
Mumbai_Employee: 1,
Mumbai_Resident: 2,
Mumbai_Worker: 1,
Hyderabad_Resident: 3,
Hyderabad_Homemaker: 2,
Hyderabad_Employee: 1
}
Alternative Approach Using reduce()
function groupAndCountWithReduce(array, prop1, prop2) {
return array.reduce((acc, obj) => {
const key = obj[prop1] + '_' + obj[prop2];
acc[key] = (acc[key] || 0) + 1;
return acc;
}, {});
}
// Using the reduce method
const resultReduce = groupAndCountWithReduce(jsonData, 'location', 'identity');
console.log("Using reduce method:");
console.log(resultReduce);
Using reduce method:
{
Kerala_Employee: 1,
Kerala_Visitor: 2,
Kerala_Worker: 1,
Mumbai_Employee: 1,
Mumbai_Resident: 2,
Mumbai_Worker: 1,
Hyderabad_Resident: 3,
Hyderabad_Homemaker: 2,
Hyderabad_Employee: 1
}
How It Works
The solution creates a unique key by combining two property values with an underscore separator. For each object in the array, it checks if this combined key already exists in the result object. If it exists, the count is incremented; otherwise, it's initialized to 1.
Time and Space Complexity
The time complexity is O(n), where n is the number of objects in the input array. The space complexity is also O(n) in the worst case, when all combinations are unique.
Common Use Cases
Analyzing user behavior data by combining demographics
Creating reports from sales data grouped by region and product
Summarizing survey responses by category combinations
Processing log data grouped by status and source
Conclusion
Grouping JSON objects by two properties and counting occurrences is a powerful technique for data analysis. Both the traditional loop approach and the modern reduce() method achieve the same result effectively, helping you transform complex datasets into meaningful summaries.
