Reputation: 139
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
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(".");
});
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>
Upvotes: 1