标签:初始 lis tms div 属性的属性 大牛 数据 匿名函数 返回
最近工作中需要写一些运营数据报表的页面,后端返回的数据都是未处理过的json,所以,大量的运算任务交给了前端来做,这其中有一个功能就是对数据进行分组,一开始我自己也尝试写了一些,但代码量比较大,显得很繁琐,直到后来在stackoverflow上看到了某位大牛写的方法,非常简洁优雅,代码如下:
function groupBy( array , f ) { let groups = {}; array.forEach( function( o ) { let group = JSON.stringify( f(o) ); groups[group] = groups[group] || []; groups[group].push( o ); }); return Object.keys(groups).map( function( group ) { return groups[group]; }); } 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, function(item){ return [item.name]; }); console.log(sorted);
[ [ { 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 } ] ]
标签:初始 lis tms div 属性的属性 大牛 数据 匿名函数 返回
原文地址:https://www.cnblogs.com/aidixie/p/12741193.html