JavaScript group a JSON Object by Two Properties and Count


The problem stated that we have to add two properties of the JSON object and count its occurrences. For example we have name and age properties in JSON then group them in a single property and count their occurrences.

What is JSON ?

JSON (Javascript Object Notation) is lightweight data to transfer between devices. It is human readable and writable data. JSON is in the form of key-value pairs. Keys are strings to define values. In JSON each entry is separated by a semicolon. For example - {“name” : “Peter”}, in this example name is a key and Peter is the value of it.

const jsonData = [
  { name: 'Aaroni', year: 2020, month: 'May' },
  { name: 'Peter', year: 2021, month: 'December' },
  { name: 'Jack', year: 2021, month: 'March' },
]

Understanding the problem

To solve this problem we will use two properties of JSON data and combine them with underscore. Then check if it is grouped together and has a property with the same value so increment the counter to 1. If no group is found then return its count to 1.

Algorithm

The algorithm below is focusing on merging two properties of a JSON object and counting its value. Follow these steps to implement the given problem-

Step 1: Define a JSON Data and give it a name jsonData.

Step 2: Declare a function called dataCount. It is taking 3 arguments, array, p1 and p2.

Step 3: Create an empty object to store the outcome JSON data.

Step 4: Initialize a for loop to iterate till the length of the array.

Step 5: Now add two properties p1 and p2 with underscore with the same index value. And assign this value in the batch variable.

Step 6: Put an if else block to check the conditions. If the group batch is not found then put its value to 1. Otherwise increment the value by 1.

Step 7: Return the value of the group, when all the elements have been iterated in for loop.

Step 8: Now call the function dataGrouped and pass the arguments.

Step 9: Print the outcome of the program.

Example

// Define array in JSON format
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"}
];



//Define function with three arguments array, p1 and p2
function dataCount(array, p1, p2) {
  const group = {};

 // initialize a for loop
  for (let i = 0; i < array.length; i++) {


    //adding properties of array with _
    const batch = array[i][p1] + '_' + array[i][p2];

    // Conditional statements if 
    if (!group[batch]) {
      group[batch] = 1;
    } else {
      group[batch]++;
    }
  }

  //return group value
  return group;
}

//Calling function with by passing arguments
const dataGrouped = dataCount(jsonData , 'location', 'identity');

//Print the output
console.log("After grouping JSON data, count is as follows")
console.log(dataGrouped); 

Output

After grouping JSON data, count is as follows
{
  Kerala_Employee: 1,
  Kerala_Visitor: 2,
  Kerala_Worker: 1,
  Mumbai_Employee: 1,
  Mumbai_resident: 1,
  Mumbai_Worker: 1,
  Mumbai_Resident: 1,
  Hyderabad_Resident: 3,
  Hyderabad_Homemaker: 2,
  Hyderabad_Employee: 1
}

In the above code we have defined an array in the form of JSON. In this data objects are divided in the form of key and value pairs. There are two keys defined first is location and second is identity. So there is some duplicate data present. We have to sort them and make a count for those data.

In the next step we have created a function to solve this problem. So basically we have passed three arguments in the function. First argument is array, second is property p1 and third is also property p2. Now the group is an empty array in the form of JSON.

Then we have initialized a for loop to run until the last index of the array. After that we have combined two properties with an underscore to get one property and assign it in a batch variable.

Now we have defined an if else block. It will check if the group is available so increase its count otherwise keep it as 1. In the last step return the group value and call the function with given arguments.

Time and Space Complexity

So we have come to the conclusion for this problem, the function dataCount() is only working for the number of elements present in the object. Then, the time complexity will be O(n). Here n is the length of the input data. And the program will take the same memory O(n), because the overall function is storing one count value per batch in the group object.

Conclusion

This is the basic functionality for working on the JSON data. We have seen how to calculate the occurrences of similar data in JSON to reduce the complexity of data and show them in another JSON object. In the program we have used only simple syntax of javascript to get the final output.

Updated on: 22-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements