JS中的groupBy⽅法
最近⼯作中需要写⼀些运营数据报表的页⾯,后端返回的数据都是未处理过的json,所以,⼤量的运算任务交给了前端来做,这其中有⼀个功能就是对数据进⾏分组,⼀开始我⾃⼰也尝试写了⼀些,但代码量⽐较⼤,显得很繁琐,直到后来在stackoverflow上看到了某位⼤⽜写的⽅法,⾮常简洁优雅,⾃⼰也进⾏修改简化。代码如下:
function groupBy( array , id ) {
let groups = {};
array.forEach( function( o ) {
let group = JSON.stringify( o[id] );
groups[group] = groups[group] || [];
groups[group].push( o );
});
return Object.values(groups);
}
let name = "name"
let list = [
{"name": "John","Average":15,"High":10,"DtmStamp":1358226000000},
{"name": "Jane","Average":16,"High":92,"DtmStamp":1358226000000},
{"name": "Jane","Average":17,"High":45,"DtmStamp":1358226000000},
{"name": "John","Average":18,"High":87,"DtmStamp":1358226000000},
{"name": "Jane","Average":15,"High":10,"DtmStamp":1358226060000},
{"name": "John","Average":16,"High":87,"DtmStamp":1358226060000},
{"name": "John","Average":17,"High":45,"DtmStamp":1358226060000},
{"name": "Jane","Average":18,"High":92,"DtmStamp":1358226060000}
];
let sorted = groupBy(list, name);
console.log(sorted);
1. 函数groupBy有两个形参,⼀为对象数组,⼆为指定分类⽅式的key;
2. groupBy函数内,先创建⼀个空对象;
3. 然后forEach遍历对象数组,遍历时要执⾏的函数中只有⼀个形参o(数组中的每个元素);
4. 由于下⾯函数调⽤是想⽤name来分组,因此let group = JSON.stringify( f(o) ),相当于先获取到对象数组list中的name属性对应的属性
值并放⼊数组中:["John"],然后再将属性值转换为json字符串:'["John"]';
5. groups[group] = groups[group] || [],在js中对象也是关联数组,因此这⾥相当于做了两件事,⼀是把group作为groups的key,⼆是将对
应的value初始化,第⼀次执⾏为空数组,循环执⾏时到相同的name时保持不变;
6. groups[group].push( o ),这句相当于把list中每个对象压⼊数组中作为value;
js 二维数组7. 最后,Object.values(groups)是取出groups对象中的所有values,返回分好了组的⼆维数组,⾄此⼤功告成~~~
[ [ { name: 'John', Average: 15, High: 10, DtmStamp: 1358226000000 },
{ name: 'John', Average: 18, High: 87, DtmStamp: 1358226000000 },
{ name: 'John', Average: 16, High: 87, DtmStamp: 1358226060000 },
{ name: 'John', Average: 17, High: 45, DtmStamp: 1358226060000 } ],
[ { name: 'Jane', Average: 16, High: 92, DtmStamp: 1358226000000 },
{ name: 'Jane', Average: 17, High: 45, DtmStamp: 1358226000000 },
{ name: 'Jane', Average: 15, High: 10, DtmStamp: 1358226060000 },
{ name: 'Jane', Average: 18, High: 92, DtmStamp: 1358226060000 } ] ]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论