0

I have a dropdown that can be toggled to 3 states - ascending, descending and none. The dropdown rearranges the items in my list.

enter image description here

My code:

list.component.html

<div *ngFor="let item of items; index as i">
  <ui-list-item
      [body]=getItem(item)"
  ></ui-list-item>
</div>

list.component.ts

getItem(item){
     const toggle = {Price: true, Active: false, Modifiers: true}
     let list = [
         {label:"Price", value:item.price}, // e.g. "$10.00"
         {label:"Active", value:item.active}, // e.g. true
         {label:"Position", value:item.position} // e.g. 1
         {label:"Category", value:item.category} // e.g. "Food"
     ];
     return list;
}

When the value in toggle is true, the items are arranged in ascending order. When the value in toggle is false, it is in descending order.

How do I implement the sort function in the order of toggle values left to right? (For example, if price comes before position, etc.) And as the labels contain different type of values, how do I detect the type and sort accordingly?

I've found this How to sort an array of objects with labels according to other array of labels? but it doesn't seem to be working.

Updated answer (but still not working)

getItem(item){
 const toggle = {Price: true, Active: false, Modifiers: true}
 let list = [
     {label:"Price", value:item.price}, // e.g. "$10.00"
     {label:"Active", value:item.active}, // e.g. true
     {label:"Position", value:item.position} // e.g. 1
     {label:"Category", value:item.category} // e.g. "Food"
 ];

list = list.sort((a: any, b: any) => {
      if (typeof toggle[a.label] === 'boolean') {
        if (toggle[a.label]) return a.value - b.value;
        else return b.value - a.value; 
      } else {
        return 0;
      }
 });

 return list;

}

Isit because I'm not retrieving the entire list to sort? Thanks for your help!

iBlehhz
  • 566
  • 5
  • 26

1 Answers1

1
list = list.sort((a:any, b:any) => {
    if(a.label !== b.label){ // if labels are not equal sort by label
        return a.label.localeCompare(b.label) 
    }
    if(typeof toggle[a.label] == 'boolean'){
      if(toggle[a.label])
        return a.value.localeCompare(b.value)
      else
        return b.value.localeCompare(a.value)
    } else {
      return 0
    }
    }
Gokul Prasannan
  • 318
  • 1
  • 4