Home > front end >  A one-dimensional array into a two dimensional array
A one-dimensional array into a two dimensional array

Time:11-19

Var json=[
{
School: "college",
Title: "mathematics",
},
{
School: "college",
Title: "mathematics",
},
{
School: "school of 3",
Title: "mathematics, 2"
},
{
School: "college",
Title: "mathematics, 3"
},
]
//to heavy
Var newarr=json. The filter ((it, index)=& gt; {
Var arrids=[]
Json. ForEach ((item, I)=& gt; {
Arrids. Push (item. The title)
})
Return arrids. IndexOf (it. The title)===index
})
//search, add
Var lidev=[]
Var arr=[]
Var cent=[]
For (var I=0; i Var obj={}
Cent=[]
For (var j=0; J & lt; Json. Length; J++) {
If (newarr [I]. Title===json [j]. Title) {
Cent. Push (json [j])
}
}
Obj. Zy=cent
Obj. Title=newarr [I]. Title
Arr. Push ({obj})
}
The console. The log (arr)

CodePudding user response:

Array. The forEach (suggested) :
 
Const newArr=[], temp={};
Arr. ForEach (item=& gt; {
if(! \ [item. The title]) {
NewArr. Push ({obj: {title: the item title, zy: [items]}});
\ [item. The title]={} index: newArr. Length - 1.
} else {
NewArr [\ [item. The title]. Index]. Obj. Zy. Push (item)
}
});
The console. The log (newArr);



Array. Reduce implementations:
 
Const result=arr. Reduce ((res: item)=& gt; {
if(! Res. \ [item. The title]) {
Res. Arr. Push ({obj: {title: the item title, zy: [items]}});
Res. \ [item. The title]={index: res. Arr.} to length - 1.
} else {
Res. Arr [\ [item. The title]. Index]. Obj. Zy. Push (item)
};
return res;
}, {arr: [], temp: {}})
The console. The log (result. Arr);
  • Related