ironman ironman -3 years ago 118
TypeScript Question

how do I display a list in a custom sort order with angular?

I'm trying to display a list of objects on screen with custom order [m,r,d,v,o].
I've tried using the sort() function which works for the first and last items but the middle comes through randomly.

Should I be using the sort() function for this situation? If so what am I doing wrong?

In the UI I'm using a *ngFor to loop through array.

<div *ngFor="let stuff of sortedStuff; let i = index;">
<div>want to display in the custom sort order here</div>
<ul><li> {{ stuff.someproperty }} <li></ul>
</div>


Code that builds the array:

var sortedStuff = stuff.splice(0);
sortedStuff.sort((obj1) => {
if (obj1.propertyX === 'M') {
return -1;
}

if (obj1.propertyX!= 'M' && obj1.propertyX!= 'D' && obj1.productType != 'V' && obj1.propertyX!= 'O' && obj1.propertyX=== 'R'){
return 1;
}

if (obj1.propertyX!= 'M' && obj1.propertyX!= 'R' && obj1.propertyX!= 'V' && obj1.propertyX!= 'O' && obj1.propertyX === 'D'){
return 1;
}

if (obj1.propertyX!= 'M' && obj1.propertyX!= 'D' && obj1.propertyX!= 'R' && obj1.propertyX!= 'O' && obj1.propertyX === 'V'){
return 1;
}

if (obj1.obj1.propertyX != 'M' && obj1.obj1.propertyX != 'D' && obj1.obj1.propertyX != 'V' && obj1.obj1.propertyX != 'R' && obj1.obj1.propertyX === 'O'){
return 1;
}
return 0;
});

Answer Source

No, you should not use sort(). A simple solution would be to just write a custom function like:

  csorts(items: string[], order: string[]) {
    let returnItems: string[] = [];
    for (let ord of order) {
      let ordered = [];
      for (let item of items) {
        if (item === ord) {
          ordered.push(item);
        }
      }
      returnItems = returnItems.concat(ordered);
    }
    return returnItems;
  }

resulting in use of:

let items = ['m','r','d','m','v','r','m','d','d','r']
let order = ['m','r','d','v','o']
let ordered = csort(items, order);
console.log(ordered);

...

[ 'm', 'm', 'm', 'r', 'r', 'r', 'd', 'd', 'd', 'v' ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download