Consolidate multiple sorting functions into a single function to effectively sort by column

Can someone help me simplify my sorting function for array columns? Currently, I have multiple functions like the one below for each column:

  sort() {
    if (this.sortAsc == false) {
      this.tab.sort((a, b) => {
        return a.name.localeCompare(b.name);
      });
      this.sortAsc = true;
    } else {
      this.tab.sort((a, b) => {
        }
        return b.name.localeCompare(a.name);
      });
      this.sortAsc = false;
    }
  }

An excerpt from the table structure:

         ...
          <tr>
              <th (click)="sort()">Name</th>
              ...
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let item of tab" (click)="getById(item.id)" tabindex="0">
            <td> {{ item.name }} </td>
            ...
          </tr>
         ...

Answer №1

If you want to sort by a specific variable, you can add a parameter to the sorting function like this: sort('name') Within the sort function, you can then utilize that parameter to determine how you want to sort.

sort(val: string) {
    if(!this.sortAsc) {
        this.tab.sort((a,b) => {
            return a[val].localeCompare(b[val]);
        });
        this.sortAsc = true;
    }
    ...
}

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

Encountered a setback while constructing a library of Angular 7 components

While I successfully created a component library in Angular version 11 without any issues, I encountered an error when trying to build a component library in Angular version 7. Cannot find module 'tsickle/src/tsickle' Require stack: - D:\Ang ...

I haven't encountered any type warnings in the places where I anticipated them

When I define an object like this: const x: { str: string, num: number } = { str: str, num: not_a_num }; I am surprised to find that even though 'not_a_num' is a string and not a number, the compiler does not throw an error. Instead, ...

Make sure a Typescript array contains a particular value

Currently, I am in the process of developing a dropdown-style component where the value and options are separate props. My goal is to incorporate Typescript to ensure that the value remains a valid option. Although I could perform this validation at runtim ...

Angular input range slider that automatically rounds decimal values from the data bindings

I've implemented a range slider within an Angular form to capture and display recorded values. <input [formControlName]="object.id" [id]="object.id" type="range" [(ngModel)]="object.answer" [step]="objec ...

Executing an individual .ts file within a Next.js application using ts-node for the purpose of testing

I'm attempting to execute a single ES module .ts file within a Next.js project using the default configuration for quick debugging: npx ts-node lib/my_module.ts However, I encounter the following error: Warning: To load an ES module, set "type&q ...

Accessing the element reference within a custom attribute directive in Angular through a projected template using ngTemplateOutlet

I'm encountering an issue when trying to adjust the css and click event on a custom attribute directive The DIV causing the problem is nested within a reference that is projected and passed into a child component. Here is the process: Add the ng-te ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

The final position of the Angular increment animation does not hold

Is there a way to trigger an animation when the value of countAllOrders changes? Specifically, I am attempting to adjust the margin of a list using keyframes in an Angular animation. Here is my HTML code: <ul class="digits" [@ordersValue]=&q ...

The Postman tool is able to provide a successful response, but when attempting to call the same API through Angular code,

After successful postman calls to the API, I encountered an error when trying to call the same API in my Angular application. The error message received from the backend is shown below: https://i.stack.imgur.com/CrMwM.png The error messages are as follow ...

Passing a type as an argument in Typescript

How can I pass a type as a parameter in Typescript? type myType = {} const passingType = (t: Type) => { const x : t = {} } passingType(myType); I keep receiving TypeScript errors. 't' is referencing a value, but it is being used as a t ...

Angular4 does not recognize this.form.get as a valid function

While working on my Angular 4 application, I encountered an issue with data binding to a form. Despite the code for binding appearing correct, there seems to be a problem that I can't quite pinpoint. Upon debugging the application, I noticed that the ...

Create an interactive and responsive user interface for Object using the Angular framework

After receiving a JSON Object from an API call with multiple string values, I need to create an Interface for this Object in the most efficient way possible. Rather than manually writing an Interface with 100 keys all of type string, is there a quicker a ...

Issue encountered when attempting to assign `fontWeight` within `makeStyles` using `theme` in Typescript: Error message states that the property is not

Currently, within my NextJS project and utilizing MUI, I am attempting to define a fontWeight property using the theme settings in the makeStyles function. Oddly enough, this issue only arises when building inside a docker container, as building locally po ...

Obtaining the dimensions of each individual child component within an NgTemplate

I have the following code snippet within my template. While I can iterate through its components using `get`, it does not return an object that allows me to access deeper into the HTML attributes. <ng-template #container></ng-template> Compon ...

Preventing duplicate actions on a Subject with Angular 7's rxjs debounceTime operator

While working on an Angular7 application, I encountered an issue where the KeyUp event of a numeric input was being captured by this specific HTML code: <input fxFlex type="number" formControlName="DM" (keyup)="changeDM()"> </div& ...

Steps for building a TypeScript project for server side using webpack

After configuring webpack to compile my project using TypeScript, I encountered an issue. The project is a server-side Node project that needs to be used as a linked library by another server-side project. When I compile it with webpack, I receive a window ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

Angular with RxJS: Observable with synchronous data flow

One of the services I have includes a method called foo. In this method, I am subscribing to an observable (http-client). foo () : boolean { let ret : false; this.http.get ("/blabla").subscribe ( (resp) => { ret = true; } return ret; ) ...