Group Array Objects Using JavaScript

Introduction

 
In client-side projects, there will be many scenarios where we need to rearrange the response API data to a comfortable array format to display it correctly. For example when we need to display Grouped format of data then we need to rearrange the response array to Grouped format.
 
In this article, we will learn how to Group Array Objects according to our requirements. We are going to learn Array object grouping using one scenario where we have one Array object and we have some expected structure of the array in which we want to arrange the array. We will achieve this by using JavaScript.
 

Original Array

 
Below is the array object that can be derived from the API response, but in our case, we are declaring a static array with sample data. We need to rearrange this array in Grouped format.
  1. originalArrObject = [    
  2.     {    
  3.         "name""ABC",    
  4.         "type""XYZ",    
  5.         "data": [    
  6.             [1234, 5678],    
  7.             [3456, 7890],    
  8.             [4321, 0987]    
  9.         ]    
  10.     },    
  11.     {    
  12.         "name""ABC",    
  13.         "type""PQR",    
  14.         "data": [    
  15.             ['abc''def'],    
  16.             ['fgh''ijk'],    
  17.             ['lmn''opq']    
  18.         ]    
  19.     },    
  20.     {    
  21.         "name""DEF",    
  22.         "type""XYZ",    
  23.         "data": [    
  24.             [1234, 5678],    
  25.             [3456, 7890],    
  26.             [4321, 0987]    
  27.         ]    
  28.     },    
  29.     {    
  30.         "name""DEF",    
  31.         "type""PQR",    
  32.         "data": [    
  33.             ['abc''def'],    
  34.             ['fgh''ijk'],    
  35.             ['lmn''opq']    
  36.         ]    
  37.     }    
  38. ]    
In the original array object, we have four objects with name, type, and data properties where data is also array objects which contain string and integer arrays. We are expected to group this array object by name or type.
 

Expected Result

 
Here is the expected array object we will get after grouping the original array. Here we will try to group using two properties. Below are the two array objects we are expecting to be grouped.
 
Group By name property
  1. groupByName = [{  
  2.     "name""ABC",  
  3.     "data": [{  
  4.         "type""XYZ",  
  5.         "data": [  
  6.             [1234, 5678],  
  7.             [3456, 7890],  
  8.             [4321, 0987]  
  9.         ]  
  10.     }, {  
  11.         "type""PQR",  
  12.         "data": [  
  13.             ['abc''def'],  
  14.             ['fgh''ijk'],  
  15.             ['lmn''opq']  
  16.         ]  
  17.     }]  
  18. }]  
Group By type property
  1. groupByType = [{  
  2.     "type""XYZ",  
  3.     "data": [{  
  4.         "name""ABC",  
  5.         "data": [  
  6.             [1234, 5678],  
  7.             [3456, 7890],  
  8.             [4321, 0987]  
  9.         ]  
  10.     }, {  
  11.         "name""DEF",  
  12.         "data": [  
  13.             [1234, 5678],  
  14.             [3456, 7890],  
  15.             [4321, 0987]  
  16.         ]  
  17.     }]  
  18. }]  

JavaScript Program to Group Data

 
Declare the Original Data before executing the further code which is given in the Original array section. Also, we have declared the blank expected array where we will store the final result that we are expecting to fetch with grouped data.
 
Below we have created the function called convertByProperty which will group our original array object to Grouped array object. We need to pass the original array, a property name that we want to group, and the second property of the object according to our scenario if we want group name property then we need to pass type as a secondary property and vise versa.
 
Function code is given below,
  1. function convertByProperty(originalObject, groupByProperty, secondProperty) {  
  2.     var finalArray = [];  
  3.     var uniqueVals = [];  
  4.     originalObject.map((i) => {  
  5.         var existingVals = uniqueVals.filter((j) => {  
  6.             return (i[groupByProperty] == j)  
  7.         });  
  8.         if (existingVals.length == 0) {  
  9.             uniqueVals.push(i[groupByProperty]);  
  10.         }  
  11.     });  
  12.     uniqueVals.map((k) => {  
  13.         var dataObj = [];  
  14.         var expectedObj = {};  
  15.         var items = originalObject.filter((l) => {  
  16.             return (l[groupByProperty] == k)  
  17.         });  
  18.         items.map((m) => {  
  19.             var obj = {};  
  20.             obj[secondProperty] = m[secondProperty];  
  21.             obj['data'] = m.data;  
  22.             dataObj.push(obj);  
  23.         });  
  24.         expectedObj[groupByProperty] = k;  
  25.         expectedObj['data'] = dataObj;  
  26.         finalArray.push(expectedObj);  
  27.     });  
  28.     return finalArray;  
Explanation
 
In the Function, first, we are fetching a unique array of property values on which we are applying group.
  1. var uniqueVals = [];  
  2. originalObject.map((i) => {  
  3.     var existingVals = uniqueVals.filter((j) => {  
  4.         return (i[groupByProperty] == j)  
  5.     });  
  6.     if (existingVals.length == 0) {  
  7.         uniqueVals.push(i[groupByProperty]);  
  8.     }  
  9. });  
After fetching the unique group by values we will loop on it and fetch matching values using filters. Then store them into a single object according to our requirement and store them into the final array. It will run for every Grouping property and bind matching values to it and finally, we get an array of grouped values in finalarray which will be returned to the function as a response.
  1. uniqueVals.map((k) => {  
  2.     var dataObj = [];  
  3.     var expectedObj = {};  
  4.     var items = originalObject.filter((l) => {  
  5.         return (l[groupByProperty] == k)  
  6.     });  
  7.     items.map((m) => {  
  8.         var obj = {};  
  9.         obj[secondProperty] = m[secondProperty];  
  10.         obj['data'] = m.data;  
  11.         dataObj.push(obj);  
  12.     });  
  13.     expectedObj[groupByProperty] = k;  
  14.     expectedObj['data'] = dataObj;  
  15.     finalArray.push(expectedObj);  
  16. });  
Running the Function
 
After defining the function we can call the convertByProperty by inserting the required values like an original array, group by the property, and secondary property.
 
We can store the result into variables and log the result array in the console. Then we will use the result array according to our requirement for displaying the grouped data.
  1. var groupByName = convertByProperty(originalArrObject, 'name''type');  
  2. var groupByType = convertByProperty(originalArrObject, 'type''name');  
  3.   
  4. console.log(groupByName);  
  5. console.log(groupByType);  
We can pass the whole code directly into the Console of the web browser to test the result. Source code is attached to the article and is downloadable as a JavaScript file.
 
Result arrays are given below,
 
Group by name
 
Group Array objects using JavaScript
 
Group by type
 
Group Array objects using JavaScript
 

Conclusion

 
In this article, we learned how to group array objects using JavaScript. If you find anything that I missed in this article please provide your valuable feedback.