【代码】JavaScript数组实现GroupBy分组

2022-05-18 10:23:48  阅读 2990 次 评论 2 条

直接上代码

//这个是带key的
Array.prototype.groupBy = function(group){
    return group && typeof group==='function'?Array.prototype.reduce.call(this,(c, v)=>{
        var k = group(v);
        if(c.hasOwnProperty(k)){
            c[k].push(v);
        } else {
            c[k] = [v];
        }
        return c;
    },{}):this;
}

//这个是不带key的,直接一个数组集合
Array.prototype.groupBy = function(group){
    var tmp_key=[];
    var res_arr=[];
    return group && typeof group==='function'?Array.prototype.reduce.call(this,(c, v)=>{
        var k = group(v);
        var key_index=tmp_key.findIndex((value,key)=>{
            return value==k;
        });
        if(key_index>-1){
            //存在
            res_arr[key_index].push(v);
        }else{
            //不存在
            tmp_key.push(k);
            key_index=tmp_key.length-1;
            res_arr[key_index]=[v];
        }		
        return res_arr;
    },{}):this;
}

调用

var arr=[
    {room:"201",name:"张三"},
    {room:"201",name:"李四"},
    {room:"201",name:"王五"},
    {room:"202",name:"赵六"},
];
var res=arr.groupBy(u=>u.room);//用哪个字段排序

返回

//带key的返回
{"201":[{"room":"201","name":"张三"},{"room":"201","name":"李四"},{"room":"201","name":"王五"}],"202":[{"room":"202","name":"赵六"}]}
//不带key的返回
[[{"room":"201","name":"张三"},{"room":"201","name":"李四"},{"room":"201","name":"王五"}],[{"room":"202","name":"赵六"}]]'



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2205
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

评论列表

  1. 访客
    访客  @回复

    学到了,学到了