Angular Material table sorting list of IPs

对着背影说爱祢 提交于 2021-01-29 08:12:07

问题


Example here

I'm not sure why Material Table sorting doesn't order the table correctly I made an example stackblitz there.

(Expected) Sorted lowest IP first

"10.16.0.8"
"10.16.0.16"
"10.16.0.32"
"10.16.10.35"
"10.16.10.64"
"10.16.10.120"

(Expected) Then you click button to sort highest and you'd get

"10.16.10.120"
"10.16.10.64"
"10.16.10.35"
"10.16.0.32"
"10.16.0.16"
"10.16.0.8"

But the current output when sorting now can be :

10.16.0.16
10.16.0.32
10.16.0.8
10.16.10.120
10.16.10.35
10.16.10.64 

回答1:


you need take account that you're orderer alphabetical (120 is less than 9), so you need transform yours IPs to get the same numbers of digits

  ipsnormalized = this.ips    //create a string separated by dots each number
                              //three digits, eg. 1.23.9.10 =>001.023.009.010
    .map(x => x.split("."))
    .map((x: string[]) => {
      return x.map(y => ("000" + y).slice(-3)).join(".");
    })
    .sort()                  //sort
    .map(x => x.split("."))  //remove the "0s"
    .map((x: string[]) => {
      return x.map(y => +y).join(".");
    });

stackblitz

Updated to sort a Mat-table, only add a new property to your data

  element = ELEMENT_DATA.map((x: any) => ({
    ...x,
    normalize: x.weight
      .split(".")
      .map((y: string[]) => ("000" + y).slice(-3))
      .join(".")
  }));
  dataSource = new MatTableDataSource(this.element);

And indicate to header this property to sort, (this mat-sort-header="normalize")

    <ng-container matColumnDef="weight" >
        <th mat-header-cell *matHeaderCellDef mat-sort-header="normalize"> Weight</th>
        <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
      </ng-container>

A new stackblitz




回答2:


Sorting is done by comparing strings, same as Java, its in "lexicographical order", you can find more in this post

If you want to sort them by number value, you need to remove the dots, and sort them while still showing the dots in the view.



来源:https://stackoverflow.com/questions/64968027/angular-material-table-sorting-list-of-ips

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