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.
- originalArrObject = [
- {
- "name": "ABC",
- "type": "XYZ",
- "data": [
- [1234, 5678],
- [3456, 7890],
- [4321, 0987]
- ]
- },
- {
- "name": "ABC",
- "type": "PQR",
- "data": [
- ['abc', 'def'],
- ['fgh', 'ijk'],
- ['lmn', 'opq']
- ]
- },
- {
- "name": "DEF",
- "type": "XYZ",
- "data": [
- [1234, 5678],
- [3456, 7890],
- [4321, 0987]
- ]
- },
- {
- "name": "DEF",
- "type": "PQR",
- "data": [
- ['abc', 'def'],
- ['fgh', 'ijk'],
- ['lmn', 'opq']
- ]
- }
- ]
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
- groupByName = [{
- "name": "ABC",
- "data": [{
- "type": "XYZ",
- "data": [
- [1234, 5678],
- [3456, 7890],
- [4321, 0987]
- ]
- }, {
- "type": "PQR",
- "data": [
- ['abc', 'def'],
- ['fgh', 'ijk'],
- ['lmn', 'opq']
- ]
- }]
- }]
- groupByType = [{
- "type": "XYZ",
- "data": [{
- "name": "ABC",
- "data": [
- [1234, 5678],
- [3456, 7890],
- [4321, 0987]
- ]
- }, {
- "name": "DEF",
- "data": [
- [1234, 5678],
- [3456, 7890],
- [4321, 0987]
- ]
- }]
- }]
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,
- function convertByProperty(originalObject, groupByProperty, secondProperty) {
- var finalArray = [];
- var uniqueVals = [];
- originalObject.map((i) => {
- var existingVals = uniqueVals.filter((j) => {
- return (i[groupByProperty] == j)
- });
- if (existingVals.length == 0) {
- uniqueVals.push(i[groupByProperty]);
- }
- });
- uniqueVals.map((k) => {
- var dataObj = [];
- var expectedObj = {};
- var items = originalObject.filter((l) => {
- return (l[groupByProperty] == k)
- });
- items.map((m) => {
- var obj = {};
- obj[secondProperty] = m[secondProperty];
- obj['data'] = m.data;
- dataObj.push(obj);
- });
- expectedObj[groupByProperty] = k;
- expectedObj['data'] = dataObj;
- finalArray.push(expectedObj);
- });
- return finalArray;
Explanation
In the Function, first, we are fetching a unique array of property values on which we are applying group.
- var uniqueVals = [];
- originalObject.map((i) => {
- var existingVals = uniqueVals.filter((j) => {
- return (i[groupByProperty] == j)
- });
- if (existingVals.length == 0) {
- uniqueVals.push(i[groupByProperty]);
- }
- });
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.
- uniqueVals.map((k) => {
- var dataObj = [];
- var expectedObj = {};
- var items = originalObject.filter((l) => {
- return (l[groupByProperty] == k)
- });
- items.map((m) => {
- var obj = {};
- obj[secondProperty] = m[secondProperty];
- obj['data'] = m.data;
- dataObj.push(obj);
- });
- expectedObj[groupByProperty] = k;
- expectedObj['data'] = dataObj;
- finalArray.push(expectedObj);
- });
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.
- var groupByName = convertByProperty(originalArrObject, 'name', 'type');
- var groupByType = convertByProperty(originalArrObject, 'type', 'name');
-
- console.log(groupByName);
- 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
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.