eternal_atom
eternal_atom

Reputation: 139

Angular Material table sorting list of IPs

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 

Upvotes: 0

Views: 720

Answers (2)

Eliseo
Eliseo

Reputation: 57971

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

Upvotes: 1

R.K
R.K

Reputation: 197

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.

Upvotes: 0

Related Questions