
//数据
let arr = [
{id:1,name:'北京',type:'985'},
{id:2,name:'上海',type:'985'},
{id:3,name:'天津',type:'211'},
{id:4,name:'广州',type:'985'},
{id:5,name:'深圳',type:'211'},
{id:6,name:'武汉',type:'985'}
]
//方法
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];
});
}
//调用
groupBy(arr, function(item) {
return item.type;
});
结果
(2) [Array(4), Array(2)]
0: Array(4)
0: {id: 1, name: "北京", type: "985"}
1: {id: 2, name: "上海", type: "985"}
2: {id: 4, name: "广州", type: "985"}
3: {id: 6, name: "武汉", type: "985"}
length: 4
[[Prototype]]: Array(0)
1: Array(2)
0: {id: 3, name: "天津", type: "211"}
1: {id: 5, name: "深圳", type: "211"}
length: 2
[[Prototype]]: Array(0)
length: 2
[[Prototype]]: Array(0)
标签: 多维数组
上面是“js将一个数组按照同一字段变成多维数组”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_1457.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

如何在Linux中利用Xen配置和管理虚拟化技术?
网站优化提高关键词排名需要原创内容吗?
盘点3A游戏《黑神话:悟空》电脑配置有要求吗?最低配置介绍
猫狸云搜索官网:一款最好用的阿里云盘资源搜索站