I have this array with parents and their children:
JavaScript
x
35
35
1
const array = [
2
{
3
'title':'America',
4
'type': 1
5
},
6
{
7
'title':'Brasil',
8
'type': 0
9
},
10
{
11
'title':'Ecuador',
12
'type': 0
13
},
14
{
15
'title':'Bolivia',
16
'type': 0
17
},
18
{
19
'title':'Europe',
20
'type': 1
21
},
22
{
23
'title':'Spain',
24
'type': 0
25
},
26
{
27
'title':'Italy',
28
'type': 0
29
},
30
{
31
'title':'Germany',
32
'type': 0
33
}
34
]
35
The problem that I have is that I need to order the children of each father, the result should be:
JavaScript
1
35
35
1
array_order = [
2
{
3
'title':'America',
4
'type': 1
5
},
6
{
7
'title':'Bolivia',
8
'type': 0
9
},
10
{
11
'title':'Brasil',
12
'type': 0
13
},
14
{
15
'title':'Ecuador',
16
'type': 0
17
},
18
{
19
'title':'Europe',
20
'type': 1
21
},
22
{
23
'title':'Germany',
24
'type': 0
25
},
26
{
27
'title':'Italy',
28
'type': 0
29
},
30
{
31
'title':'Spain',
32
'type': 0
33
}
34
]
35
That is the only information I have, the father has type 1 and his children are next in the list types 0.
Any help please.
Thanks.
By the way, I have tried this but I’m stucked:
JavaScript
1
22
22
1
let expTempFull = [];
2
let expTempFirst = [];
3
expTemp.forEach((el)=>{
4
if (el.type == 1){
5
if (expTempFirst.length == 0){
6
expTempFull.push(el);
7
}else{
8
expTempFirst = expTempFirst.sort((a, b) => a.title.localeCompare(b.title));
9
expTempFirst.forEach((ex)=>{
10
expTempFull.push(ex);
11
});
12
expTempFirst = [];
13
expTempFull.push(el);
14
}
15
} else {
16
expTempFirst.push(el);
17
if (el.title === expTemp[expTemp.length - 1].title){
18
expTempFull.push(el);
19
}
20
}
21
});
22
Advertisement
Answer
You could treat any same type as own group, sort them and take a flat array as result.
JavaScript
1
11
11
1
const
2
array = [{ title: 'America', type: 1 }, { title: 'Brasil', type: 0 }, { title: 'Ecuador', type: 0 }, { title: 'Bolivia', type: 0 }, { title: 'Europe', type: 1 }, { title: 'Spain', type: 0 }, { title: 'Italy', type: 0 }, { title: 'Germany', type: 0 }],
3
result = array
4
.reduce((r, o, i) => {
5
if (!i || r[r.length - 1][0].type !== o.type) r.push([]);
6
r[r.length - 1].push(o);
7
return r;
8
}, [])
9
.flatMap(array => array.sort((a, b) => a.title.localeCompare(b.title)));
10
11
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }