Grouping array values in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of objects containing some years and weeks data like this −

const arr = [
   {year: 2017, week: 45},
   {year: 2017, week: 46},
   {year: 2017, week: 47},
   {year: 2017, week: 48},
   {year: 2017, week: 50},
   {year: 2017, week: 52},
   {year: 2018, week: 1},
   {year: 2018, week: 2},
   {year: 2018, week: 5}
];

We are required to write a JavaScript function that takes in one such array. The function should return a new array where all the objects that have common value for the "year" property are grouped into a separate object.

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

[
   { 2017 : [{
      week: 45,
      week: 46,
      week: 47,
      week: 48,
      week: 50,
      week: 53
   },
   { 2018 : [{
      week: 1,
      week: 2,
      week: 5
   }]
]

Example

The code for this will be −

const arr = [
   {year: 2017, week: 45},
   {year: 2017, week: 46},
   {year: 2017, week: 47},
   {year: 2017, week: 48},
   {year: 2017, week: 50},
   {year: 2017, week: 52},
   {year: 2018, week: 1},
   {year: 2018, week: 2},
   {year: 2018, week: 5}
];
const groupByYear = arr => {
   const res = [];
   const map = {};
   arr.forEach(item => {
      const temp = {};
      if (!map[item.year]) {
         map[item.year] = [];
         temp[item.year] = map[item.year];
         res.push(temp);
      };
      map[item.year].push({ value: item.week });
   });
   return res;
};
console.log(JSON.stringify(groupByYear(arr), undefined, 4));

Output

The output in the console −

[
   {
      "2017": [
         {
            "value": 45
         },
         {
            "value": 46
         },
         {
            "value": 47
         },
         {
            "value": 48
         },
         {
            "value": 50
         },
         {
            "value": 52
         }
      ]
   },
   {
      "2018": [
         {
            "value": 1
         },
         {
            "value": 2
         },
         {
            "value": 5
         }
      ]
   }
]
raja
Published on 12-Oct-2020 15:15:16
Advertisements