在JavaScript中对数组值进行分组

假设我们有一个包含一些年和周数据的对象数组,如下所示:

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}
];

我们需要编写一个包含一个这样的数组的JavaScript函数。该函数应返回一个新数组,在该数组中,所有对“ year”属性具有相同值的对象都被分组到一个单独的对象中。

因此,上述数组的输出对象应类似于-

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

示例

为此的代码将是-

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));

输出结果

控制台中的输出-

[
   {
      "2017": [
         {
            "value": 45
         },
         {
            "value": 46
         },
         {
            "value": 47
         },
         {
            "value": 48
         },
         {
            "value": 50
         },
         {
            "value": 52
         }
      ]
   },
   {
      "2018": [
         {
            "value": 1
         },
         {
            "value": 2
         },
         {
            "value": 5
         }
      ]
   }
]