0

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 

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thanks for the help!
Amazing! This is a really nice fix, I'd have never thought of it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.