最近工做中須要寫一些運營數據報表的頁面,後端返回的數據都是未處理過的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);
具體實現思路:json
結果以下:後端
[ [ { 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 } ] ]