Ordering a list of IP addresses using Angular Material table sorting

Here is an example

I am baffled by the fact that Material Table sorting does not properly arrange the table. I have created a stackblitz example to demonstrate this.

Expected order - Sorting 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"

After clicking the button to sort highest, the expected output would be:

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

However, the current output when sorting now may look like:

10.16.0.16
10.16.0.32
10.16.0.8
10.16.10.120
10.16.10.35
10.16.10.64 

Answer №1

It's important to consider that when ordering alphabetically, numbers with fewer digits come before those with more digits (e.g., 120 is less than 9). To ensure proper sorting, you may need to transform your IPs to have the same number of digits.

ipsNormalized = this.ips   
    .map(x => x.split("."))
    .map((x: string[]) => {
      return x.map(y => ("000" + y).slice(-3)).join(".");
    })
    .sort()                  
    .map(x => x.split("."))  
    .map((x: string[]) => {
      return x.map(y => +y).join(".");
    });

Check out the example on StackBlitz

To update: To sort a Mat-table, simply add a new property called "normalize" 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);

Specify this new property in the header for sorting purposes (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>

Here is a new StackBlitz example

Answer №2

Arranging items is accomplished by evaluating strings, akin to Java, it follows the "lexicographical order", for further details refer to this article

To organize them based on numerical value, dots must be eliminated, and the arrangement should retain the appearance of dots in the display.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am struggling to grasp the concept of ref unwrapping within a TypeScript template

I'm currently in the process of converting some Vue3 code from javascript to typescript, and I am struggling to comprehend the unwrapping of a ref/computed value in the template. I used to believe that the template would automatically unwrap reactiv ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

Access to the 'currentUrlTree' property is restricted to the 'Router' class as it is marked as private and cannot be accessed externally

Currently, I am in the process of developing a login feature using jwt. However, I am encountering an error when attempting to retrieve the current URL of the active route as shown below. Error Message: [default] /Users/~/src/app/app.component.ts:51:75 P ...

What is the right way to configure an Axios Interceptor in a ReactJS app using TypeScript?

While I typically use JS with React, I decided to switch to Typescript. However, I've been encountering an error when trying to initialize a request interceptor instance: src/utils/services/axios.service.ts:16:8 TS2322: Type '{ 'Content-Type ...

The element 'mat-tab' does not recognize the property 'active', therefore it cannot be bound

I keep encountering this error even though I have already imported MatTabsModule. Below is the structure of my component: @Component({ selector: 'app-settings-page', template: ` <mat-tab-group animationDuration="0ms"> <mat-tab *n ...

Steps to change the default sort arrow icon in ag-grid to a custom SVG icon

Would greatly appreciate any assistance with this. I have reviewed the documentation, but it's still unclear to me. ...

What are some methods to troubleshoot $injector type errors in TypeScript?

I'm currently facing an issue with my AngularJS code. Here is a snippet of what I have: this.$injector.get('$state').current.name !== 'login' But, it's giving me the following error message: error TS2339: Property 'c ...

Obtaining data attributes in Angular 8

I'm working with Angular 8 and I came across an issue. In my code snippet, there are two data attributes assigned to a button element, but only one attribute is showing up. Is this a syntax error or a bug? <button [attr.data-popolamento]="all" [a ...

Utilizing Mongoose RefPath in NestJS to execute populate() operation

After registering my Schema with mongoose using Dynamic ref, I followed the documentation available at: https://mongoosejs.com/docs/populate.html#dynamic-ref @Schema({ collection: 'quotations' }) export class QuotationEntity { @Prop({ r ...

Angular2 displays an error stating that the function start.endsWith is not recognized as a valid function

After switching my base URL from / to window.document.location, I encountered the following error message: TypeError: start.endsWith is not a function Has anyone else experienced this issue with [email protected]? ...

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

The data type 'string' cannot be assigned to type 'E164Number' in the react-phone-number-input component

I'm currently utilizing a library called react-phone-number-input. Within my project, I have two important files: index.tsx and useLogicRegister.ts. While working on my code, I encountered an error stating Type 'string' is not assignable to ...

Is it normal for TypeScript to not throw an error when different data types are used for function parameters?

function add(a:number, b:number):number { return a+b; } let mynumber:any = "50"; let result:number = add(mynumber, 5); console.log(result); Why does the console print "505" without throwing an error in the "add" function? If I had declared mynumber ...

How to Customize Bootstrap Colors Globally in Angular 4 Using Code

I am interested in developing a dynamic coloring system using Angular. I have set up a service with four predefined strings: success, info, warning, and danger, each assigned default color codes. My goal is to inject this service at the root of my applicat ...

Next.js version 13 will now display the loading.tsx component whenever a setter function for useState() is

I am facing an issue with my client component that has a simple text field which utilizes the useState() hook. Every time I modify the text and call onChange, the loading UI defined in loading.tsx appears before the updated UI. However, this process causes ...

Is it possible for an app's feature module to access routing configurations from another lazily loaded module in Angular routing?

The functionality of our App is divided into multiple feature modules that are lazily loaded. Each module is loaded under different path matches, and some modules import a shared module containing reusable components. Everything seems to be working well so ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

Exploring the differences in object shapes using TypeScript

I'm currently working on defining an object that has the ability to hold either data or an error. export type ResultContainer = { data: any; } | { error: any; }; function exampleFunction():ResultContainer { return { data: 3 } } ...

Establish a local binding context within an Angular template

If I have a complex object structure that I need to bind to: <div>{{model.rootProperty}}</div> <div> <div>{{model.some.deeply.nested.property.with.a.donut.name}}</div> <div>{{model.some.deeply.nested.property.w ...