JS中的groupBy方法

最近工做中須要寫一些運營數據報表的頁面,後端返回的數據都是未處理過的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

  1. 函數groupBy有兩個形參,一爲對象數組,二爲匿名函數(該函數功能:返回對象的某個指定屬性的屬性值並存放在數組中);
  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;
  7. 最後,Object.keys(groups)是取出groups對象中的全部key,而後遍歷一個個key組成的新數組,返回分好了組的二維數組,至此大功告成~~~

結果以下:後端

[ [ { 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 } ] ]
相關文章
相關標籤/搜索