how sort array with object by property use ngFor

Issue

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);

Answered By – maaajo

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.