JavaScript Separate objects based on properties

JavascriptWeb DevelopmentFront End Technology

Suppose, we have an object like this −

const obj = {
   0: { "time": 1, "day": 1, },
   1: { "time": 2, "day": 1, },
   2: { "time": 3, "day": 1, },
   3: { "time": 1, "day": 2, },
   4: { "time": 2, "day": 2, },
   5: { "time": 3, "day": 2, }
};

We are required to write a JavaScript function that takes one such object and groups all the key value pairs in separate sub objects that have the same value for the day key.

Output

The output for the above object should be −

const output = { '1':
{ '1': { time: 1, day: 1 },
'2': { time: 2, day: 1 },
'3': { time: 3, day: 1 } },
'2':
{ '1': { time: 1, day: 2 },
'2': { time: 2, day: 2 },
'3': { time: 3, day: 2 } }
}

Example

The code for this will be −

const obj = {
   0: { "time": 1, "day": 1, },
   1: { "time": 2, "day": 1, },
   2: { "time": 3, "day": 1, },
   3: { "time": 1, "day": 2, },
   4: { "time": 2, "day": 2, },
   5: { "time": 3, "day": 2, }
};
const groupObject = obj => {
   let res = {};
   res = Object.values(obj).reduce((acc, val) => {
      if(acc[val['day']] === undefined){
         acc[val['day']] ={};
      };
      acc[val['day']][val['time']] = val;
      return acc;
   },{});
   return res;
};
console.log(groupObject(obj));

Output

The output in the console −

{
   '1': {
      '1': { time: 1, day: 1 },
      '2': { time: 2, day: 1 },
      '3': { time: 3, day: 1 }
   },
   '2': {
      '1': { time: 1, day: 2 },
      '2': { time: 2, day: 2 },
      '3': { time: 3, day: 2 }
   }
}
raja
Published on 12-Oct-2020 11:00:51
Advertisements