I have a array of unsorted "Edition" objects.
export interface Edition {
name: string;
edition_code: string;
parent_code: string;
released_at: number;
}
The attributes name, edition_code and released_at are set on every object. The attribute parent_code can be null.
An edition object with no parent_code is a parent edition. All edition objects where the parent_code is equal to the parent edition's edition_code are child editions of this parent edition.
I try to sort an array by the following conditions:
All parent editions must be sorted by
released_at(newest first)- A parent edition can have zero ore more child editions
Every child edition has to be sorted directy after the matching parent edition object. (ignoring the
released_atattribute)- The child editions must be sorted alphabetically by their names.
I am trying to sort the array with the sort() method. The allEditions()-method returns an Observable<Array<Edition>>
this.dataSource = this.editionService.allEditions().pipe(
map((editions) =>
editions
.sort((a, b) => {
// this is the point where i struggle to create the correct sorting function
})
)
);
Example:
This is an example of an unsorted array:
[
{
"name": "Stomper";
"edition_code": "sto";
"parent_code": null;
"released_at": "1587679200000";
},
{
"name": "Flyer";
"edition_code": "fly";
"parent_code": null;
"released_at": "1619128800000";
},
{
"name": "Stomper Promos";
"edition_code": "psto";
"parent_code": "sto";
"released_at": "1587679200000";
},
{
"name": "Stomper Ultra";
"edition_code": "usto";
"parent_code": "sto";
"released_at": "1587679200000";
},
{
"name": "Flyer Special";
"edition_code": "sfly";
"parent_code": "fly";
"released_at": "1619128800000";
},
{
"name": "Stomper Extras";
"edition_code": "esto";
"parent_code": "sto";
"released_at": "1587679200000";
},
{
"name": "Roller";
"edition_code": "rol";
"parent_code": null;
"released_at": "1374184800000";
},
{
"name": "Flyer Reloaded";
"edition_code": "rfly";
"parent_code": "fly";
"released_at": "1493330400000";
}
]
This is the exact same array but sorted:
[
{
"name": "Flyer";
"edition_code": "fly";
"parent_code": null;
"released_at": "1619128800000";
},
{
"name": "Flyer Reloaded";
"edition_code": "rfly";
"parent_code": "fly";
"released_at": "1493330400000";
},
{
"name": "Flyer Special";
"edition_code": "sfly";
"parent_code": "fly";
"released_at": "1619128800000";
},
{
"name": "Stomper";
"edition_code": "sto";
"parent_code": null;
"released_at": "1587679200000";
},
{
"name": "Stomper Extras";
"edition_code": "esto";
"parent_code": "sto";
"released_at": "1587679200000";
},
{
"name": "Stomper Promos";
"edition_code": "psto";
"parent_code": "sto";
"released_at": "1587679200000";
},
{
"name": "Stomper Ultra";
"edition_code": "usto";
"parent_code": "sto";
"released_at": "1587679200000";
},
{
"name": "Roller";
"edition_code": "rol";
"parent_code": null;
"released_at": "1374184800000";
}
]