how sort array with object by property use ngFor

陌路散爱 提交于 2020-08-10 18:22:26

问题


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


回答1:


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



回答2:


you should use a pipe to sort the data before the show in view:

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

in sort pipe, you can use :

 array.sort(function(obj1, obj2) {
   return obj1.idx > obj2.idx;
});



回答3:


You can just use sorting arrays:

function sortFunc(a, b) {
  if ( a.index < b.index ){
    return -1;
  }
  if ( a.index > b.index ){
    return 1;
  }
  return 0;
}

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}
].sort(sortFunc);

Or you can use lodash orderBy https://lodash.com/docs/4.17.11#orderBy




回答4:


Here is OrderBy pipe library is available.
https://github.com/VadimDez/ngx-order-pipe

 npm install ngx-order-pipe --save


来源:https://stackoverflow.com/questions/56125874/how-sort-array-with-object-by-property-use-ngfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!