直接上代码
//这个是带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":"赵六"}]]'
微信扫码查看本文
发表评论