manou
manou

Reputation: 133

Sort by specific custom type in angular

I have a list of elements which one of the property is type, adn its values: { footprint, platform, roving } I am trying to sort the list following the next criteria: platform > footprint > roving

Since alphbetical order footprint is before platform, sorting by the field is not working as expected and I don't know exactly how to implement a custom sort callback to do it. I am using https://vadimdez.github.io/ngx-order-pipe/ module and here is my try:

template

...
 <tr *ngFor="let platform of platforms | orderBy: order: false: true: sortCriteria; let i = index;">
...
...

component

...
order: string[] = ['type', 'name'];
...
  sortCriteria(itemA, itemB) {
    if (itemA.type == 'platform') return 1;
    if (itemB.type == 'platform') return -1;
    if ((itemA.type == 'footprint') && (itemB.type == 'roving')) return 1
    if (itemA.type == 'roving') return -1
  }    
...

I will appreciate some ideas to get this sort works as expected.

Upvotes: 0

Views: 904

Answers (1)

Karol T
Karol T

Reputation: 1136

You can create an 'order array' and fill it with correct order that do you want to use. Then use simple code:

let typesOrder = ['platform', 'footprint', 'roving'];

sortCriteria(itemA, itemB) {
    return typesOrder.indexOf(itemA.type) < typesOrder.indexOf(itemB.type);
}    

Upvotes: 3

Related Questions