对 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 函数,此函数接收一个这样的数组。该函数应该返回一个新数组,其中所有具有 "年份" 属性的相同值的对象都分组到一个单独的对象中。
因此,以上数组的输出对象应如下所示 −
[ { 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 } ] } ]
广告