Grouping data to monthwise in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have some data about some users like this −

const obj = {
   "Mary": {
      "2016-1": 2,
      "2016-5": 1,
      "2016-3": 1
   },
   "Paul": {
      "2016-1": 1,
      "2016-3": 1
   },
   "moth": {
      "2016-1": 2,
   "2016-5": 1
   }
};

We are required to write a JavaScript function that takes in one such object. Our function should group this user data into objects where each unique date is represented by an object.

Example

The code for this will be −

const obj = {
   "Mary": {
      "2016-1": 2,
      "2016-5": 1,
      "2016-3": 1
   },
   "Paul": {
      "2016-1": 1,
      "2016-3": 1
   },
   "moth": {
      "2016-1": 2,
      "2016-5": 1
   }
};
const groupByDate = (obj = {}) => {
   const names = Object.keys(obj);
   const res = {};
   for(let i = 0; i < names.length; i++){
      const name = names[i];
      const dates = Object.keys(obj[name]);
      for(let j = 0; j < dates.length; j++){
         const date = dates[j];
         if(!res.hasOwnProperty(date)){
            res[date] = {
               names: [name],
               values: [obj[name][date]]
            }
         }
         else{
            res[date].names.push(name);
            res[date].values.push(obj[name][date]);
         };
      };
   };
   return res;
};
console.log(groupByDate(obj));

Output

And the output in the console will be −

{
   '2016-1': { names: [ 'Mary', 'Paul', 'moth' ], values: [ 2, 1, 2 ] },
   '2016-5': { names: [ 'Mary', 'moth' ], values: [ 1, 1 ] },
   '2016-3': { names: [ 'Mary', 'Paul' ], values: [ 1, 1 ] }
}
raja
Published on 23-Nov-2020 10:00:26
Advertisements