數組元素按照某個key分類轉換成二維數組
let test =[
{id:0,code:"4"},
{id:1,code:"1"},
{id:2,code:"1"},
{id:3,code:"2"},
{id:4,code:"2"},
{id:5,code:"3"},
{id:6,code:"4"},
{id:7,code:"1"},
{id:8,code:"5"},
];
function classify(arr,key) {
let obj = {};
arr.forEach((e)=>{
if(typeof obj[e[key]]=='undefined'){
obj[e[key]] = []
}
obj[e[key]].push(e)
});
return Object.values(obj)
}
console.log(classify(test,"code"))
效果圖: