Group objects inside the nested array JavaScript


Let’s say e have a parentArray that contains many sub arrays each of the same size, each sub array is an array of objects containing two properties: key and value. Within a subarray it is confirmed that two objects cannot have the same key but all subarrays have the same pair of n keys where n is the size of the sub array.

Our job is to prepare an object with key as key of objects and value being an array that contains all the values for that particular key.

Here is our sample parent array −

const parentArray = [[
   {
      key: 123,
      value: 'India'
   }, {
      key: 124,
      value: 'USA'
   }, {
      key: 125,
      value: 'Japan'
   }, {
      key: 126,
      value: 'Denmark'
   }, {
         key: 127,
      value: 'Austria'
   },
], [
   {
      key: 124,
      value: 'Kenya'
   }, {
      key: 126,
      value: 'UK'
   }, {
      key: 123,
      value: 'Germany'
   }, {
      key: 127,
      value: 'Spain'
   }, {
      key: 125,
      value: 'Portugal'
   },
]];

We will iterate over the parent array and then all of the sub arrays one by one and if we find a matching key, we push it into the value array otherwise we create a new value array.

The full code for this will be −

Example

const parentArray = [[
   {
      key: 123,
      value: 'India'
   }, {
      key: 124,
      value: 'USA'
   }, {
      key: 125,
      value: 'Japan'
   }, {
      key: 126,
      value: 'Denmark'
   }, {
      key: 127,
      value: 'Austria'
   },
], [
   {
      key: 124,
      value: 'Kenya'
   }, {
      key: 126,
      value: 'UK'
   }, {
      key: 123,
      value: 'Germany'
   }, {
      key: 127,
      value: 'Spain'
   }, {
      key: 125,
      value: 'Portugal'
   },
]];
const map = {};
parentArray.forEach(arr => {
   arr.forEach(obj => {
      const { key, value } = obj;
      if(map[key]){
         map[key].push(value);
      }else{
         map[key] = [value]
      }
   })
});
console.log(map);

Output

The output in the console will be −

{
   '123': [ 'India', 'Germany' ],
   '124': [ 'USA', 'Kenya' ],
   '125': [ 'Japan', 'Portugal' ],
   '126': [ 'Denmark', 'UK' ],
   '127': [ 'Austria', 'Spain' ]
}

Updated on: 19-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements