I have an array of objects:
const arr = [
{
name: Exhibit A
},
{
name: Exhibit A1
},
{
name: Exhibit A2
},
{
name: Exhibit B
},
{
name: Exhibit C
},
{
name: Exhibit C1
},
{
name: Exhibit C2
},
{
name: Exhibit C3
},
]
I need to sort it reverse but Exhibits without numbers should first be in its group.
Smth like that:
const result = [
{
name: Exhibit C
},
{
name: Exhibit C3
},
},
{
name: Exhibit C2
},
},
{
name: Exhibit C1
},
{
name: Exhibit B
},
{
name: Exhibit A
},
{
name: Exhibit A2
},
{
name: Exhibit A1
}
]
const result = [...arr].sort((a, b) => {???})
Simple localeCompare didn't work as I want, so I need to find another approach.
Any ideas?
UPD: I've tried smth like this:
arr.sort((a, b) => {
const [fullA, exhibitA, numberA] = a.name.match(/Exhibit\s([^0-9]+)(\d?)/)
const [fullB, exhibitB, numberB] = b.name.match(/Exhibit\s([^0-9]+)(\d?)/)
if (exhibitA === exhibitB) {
if (!numberB || !numberA) {
return 1;
}
if (numberA && numberB) {
if (numberB > numberA) {
return 1;
}
if (numberB > numberA) {
return -1;
}
}
return 0;
}
return b.name.localeCompare(a.name);
})
It's almost what I needed, but Exhibits with the same letter has straight order, not reversed