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


i'm trying display list of objects on screen custom order [m,r,d,v,o]. i've tried using sort() function works first , last items middle comes through randomly.

should using sort() function situation? if doing wrong?

in ui i'm using *ngfor loop through array.

<div *ngfor="let stuff of sortedstuff; let = index;">     <div>want display in custom sort order here</div>     <ul><li> {{ stuff.someproperty }} <li></ul> </div> 

code builds 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; }); 

no, should not use sort(). simple solution write custom function like:

  csorts(items: string[], order: string[]) {     let returnitems: string[] = [];     (let ord of order) {       let ordered = [];       (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' ] 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -