Grouping nested array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of values like this −

const arr = [
   {
      value1:[1,2],
      value2:[{type:'A'}, {type:'B'}]
   },
   {
      value1:[3,5],
      value2:[{type:'B'}, {type:'B'}]
   }
];

We are required to write a JavaScript function that takes in one such array. Our function should then prepare an array where the data is grouped according to the "type" property of the objects.

Therefore, for the above array, the output should look like −

const output = [
   {type:'A', value: [1,2]},
   {type:'B', value: [3,5]}
];

Example

The code for this will be −

const arr = [
   {
      value1:[1,2],
      value2:[{type:'A'}, {type:'B'}]
   },
   {
      value1:[3,5],
      value2:[{type:'B'}, {type:'B'}]
   }
];
const groupValues = (arr = []) => {
   const res = [];
   arr.forEach((el, ind) => {
      const thisObj = this;
      el.value2.forEach(element => {
         if (!thisObj[element.type]) {
            thisObj[element.type] = {
               type: element.type,
               value: []
            }
            res.push(thisObj[element.type]);
         };
         if (!thisObj[ind + '|' + element.type]) {
            thisObj[element.type].value =
            thisObj[element.type].value.concat(el.value1);
            thisObj[ind + '|' + element.type] = true;
         };
      });
   }, {})
   return res;
};
console.log(groupValues(arr));

Output

And the output in the console will be −

[
   { type: 'A', value: [ 1, 2 ] },
   { type: 'B', value: [ 1, 2, 3, 5 ] }
]
raja
Published on 23-Nov-2020 15:17:01
Advertisements