Search code examples
javascriptangularsortingngfor

how sort array with object by property use ngFor


I neet to display in table sort data

js

let array = [
  { idx: number, name: string, btn: number, index: number },
  { idx: number, name: string, btn: number, index: number },
  { idx: number, name: string, btn: number, index: number }
]

html

<tr *ngFor="let ticket of array">
  <td>{{ ticket.name }}</td>
  <td>{{ ticket.btn }}</td>
  <td>{{ ticket.index }}</td>
<tr>
    

I need sort display by index value


Solution

  • let array = [
      { idx: 1, name: 'a', btn: 1, index: 2 },
      { idx: 2, name: 'b', btn: 2, index: 3 },
      { idx: 3, name: 'c', btn: 3, index: 1 }
    ];
    
    // descending
    let newarr = array.sort((a, b) => b.index - a.index);
    
    //ascending
    let newarr = array.sort((a, b) => a.index - b.index);
    
    console.log(newarr);