Skip to content

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);

具体实现思路:

函数groupBy有两个形参,一为对象数组,二为匿名函数(该函数功能:返回对象的某个指定属性的属性值并存放在数组中);

groupBy函数内,先创建一个空对象;

然后forEach遍历对象数组,遍历时要执行的函数中只有一个形参o(数组中的每个元素);

由于下面函数调用是想用name来分组,因此let group = JSON.stringify( f(o) ),相当于先获取到对象数组list中的name属性对应的属性值并放入数组中:["John"],然后再将属性值转换为json字符串:'["John"]';

groups[group] = groups[group] || [],在js中对象也是关联数组,因此这里相当于做了两件事,一是把group作为groups的key,二是将对应的value初始化,第一次执行为空数组,循环执行时找到相同的name时保持不变;

groups[group].push( o ),这句相当于把list中每个对象压入数组中作为value; 最后,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 } ] ]

相关

function groupBy(list, name) {
  return list.reduce((obj, item) => {
    if (!obj[item[name]]) {
      obj[item[name]] = []
      obj[item[name]].push(item)
    } else {
      obj[item[name]].push(item)
    }
    return obj
  }, {})
}

const g = groupBy(list, 'name')

文章来源于自己总结和网络转载,内容如有任何问题,请大佬斧正!联系我