js将一个数组按照同一字段变成多维数组

2024年08月02日 建站教程

//数据
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)

本文链接:http://so.lmcjl.com/news/9789/

展开阅读全文
相关内容