I need to rearrange the elements in an array to form groups. The first element should be one with a uniqueID and empty parentDocId, followed by elements with parentDocId matching the uniqueID of the first element. Elements with an empty parentDocId and no parent uniqueID should be placed at the bottom of the array.
Here's an example of my expected output:
[
{
name: 9,
uniqueID: '22222',
parentDocId: '',
},
{
name: 11,
uniqueID: '3463452345',
parentDocId: '22222',
},
{
name: 15,
uniqueID: '3333',
parentDocId: '',
},
{
name: 19,
uniqueID: '234235346',
parentDocId: '3333',
},
{
name: 346345,
uniqueID: '11111',
parentDocId: '',
},
{
name: 7,
uniqueID: '456456456',
parentDocId: '11111',
},
{
name: 55,
uniqueID: '346345345',
parentDocId: '',
},
{
name: 77,
uniqueID: '568567568567',
parentDocId: '',
},
];
And here's what I currently get:
[
{
"name": 55,
"uniqueID": "346345345",
"parentDocId": ""
},
{
"name": 77,
"uniqueID": "568567568567",
"parentDocId": ""
},
{
"name": 7,
"uniqueID": "456456456",
"parentDocId": "11111"
},
{
"name": 346345,
"uniqueID": "11111",
"parentDocId": ""
},
{
"name": 19,
"uniqueID": "234235346",
"parentDocId": "3333"
},
{
"name": 15,
"uniqueID": "3333",
"parentDocId": ""
},
{
"name": 11,
"uniqueID": "3463452345",
"parentDocId": "22222"
},
{
"name": 9,
"uniqueID": "22222",
"parentDocId": ""
}
]
This is the code that I am using:
items.sort((a, b) => {
if (a.parentDocId === b.uniqueID) {
return -1;
} else if (b.parentDocId === a.uniqueID) {
return 1;
} else if (a.parentDocId === '' && b.parentDocId !== '') {
return -1;
} else if (a.parentDocId !== '' && b.parentDocId === '') {
return 1;
} else {
return 0;
}
});