Arranging in ascending and descending sequence in Angular2

Is there a way to implement sorting in both ascending and descending order? I currently have code that only allows for sorting in ascending order by name and identifier. How can I modify it to also support sorting in descending order?

sortType(sort: string){
    if(sort === 'id') {
        this.projects = this.projects.sort(this.sortByID); 
        console.log(this.projects);
    }

    if(sort === 'name') {
        this.sprWellpads = this.projects.sort(this.sortByName); 
        console.log(this.projects);
    }
}

sortByName(a: Project, b: Project){
  if(a.name > b.name)  return 1
    else if (a.name == b.name)return 0
  else return -1
}

sortByID(a: Project, b: Project){
    return parseInt(a.id.toString())-parseInt(b.id.toString());
}

html:

<a class="sorting" (click)="sortType('id')" [class.active]="sortBy === 'id'" ><a class="title">ID⬇</a></a>
<a class="sorting" (click)="sortType('name')" [class.active]="sortBy === 'name'"><a class="title">Name⬇</a></a>

Answer №1

If you need to sort an object array using TypeScript, you can follow these steps:

let values = ["B_Value", "C_Value", "A_Value"];

// Ascending order

values.sort((a,b) => 0 - (a > b ? -1 : 1));

// Descending order

values.sort((a,b) => 0 - (a > b ? 1 : -1));

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

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

Tips for utilizing PINO to write logs to both file and console

I have successfully implemented logging to a log file using Pino. However, I am wondering if there is a way to also log to the console in order to manage the frequency of 'console.log()' calls. Node Version : 21.6.1 Typescript Version : 5.3.3 Pi ...

I am a beginner in the world of Typescript/Angular, and I have encountered a compiling error TS2339. It seems that even when the condition *ngIf="x.length > 0;" should be false, the

I'm currently enrolled in a Typescript/Angular course where I am learning about the implementation of "*ngIf". During one of the lessons, the instructor provided an example using an empty array to demonstrate how it fails the condition and results in ...

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

Utilize the optional chaining feature when accessing properties that may be optional

I recently encountered an issue in my Typescript project where accessing properties or functions of optional properties did not throw any errors. Here is an example: type Example = { bar?: string[] } const foo: Example = {} // Although no error occu ...

Navigating through Observables in Angular Applications

In my Angular application, I am utilizing the RxJs library to retrieve data from a backend API server. The method for this call is shown below: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const self = this; const ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

When parameters are added to one route, all other routes cease to function properly

After I added a parameter to one of the routes, all the other routes stopped rendering correctly (i.e., router-view is not working at all). The route /download/:id works as expected. Am I missing something in the setup? I tried leaving and removing the /do ...

What could be causing the increased build size of my Polymer2 compared to Angular5?

After reading multiple blogs, I decided to go with the polymer2 framework instead of angular. Some sources claimed that Polymer contributes less to the build size for production compared to angular2/5. To test this theory, I created two demo projects - on ...

TypeScript making erroneous assumptions about property values post-setting

My TypeScript object has a boolean property that causes some confusion. When I update the object's value to false, TypeScript seems to believe it will remain false indefinitely (at least within the scope), even though it can be modified: const obj = { ...

Converting an Angular1 App into a VueJs app: A step-by-step guide

Let's dive right in: I'm embarking on the journey of revamping an app that originally utilized Angular 1, but this time around I'll be harnessing the power of VueJS 2. As someone unfamiliar with Angular 1, I'm faced with some perplexing ...

Using Visual Studio Code, the next app created with nx now supports relative imports

I am encountering a problem with a Next.js project set up using nx and VS Code: When trying to automatically import a component in VS Code, it generates an absolute import which then triggers the @nrwl/nx/enforce-module-boundaries eslint rule, rendering t ...

When it comes to providedIn in Angular, which of 'root', 'platform', or 'any' is the preferred choice for different scenarios?

When it comes to providedIn in Angular, which option out of 'root', 'platform', 'any' should be the preferred choice in different cases? https://angular.io/api/core/Injectable 'root' : The application-level injec ...

Utilize ngSwitch in Angular 5 for dynamically rendering either text or textarea content

My goal is to utilize ngSwitch in order to dynamically display either text or a text area based on the Format Type ID. Each question should either display a text area or an input text field. However, currently, the text area is being displayed for every F ...

Obtaining context from a higher order component in the constructor of a child component: tips and tricks

In order to gain access to context throughout the application, I've implemented the following context provider: import React, { Component, useContext } from 'react'; import { appInitialization, Context } from "@microsoft/teams-js"; ...

Some code paths fail to return a value in Google Cloud Function callable functions

When utilizing async functions in my cloud function and including a 'return' statement in each potential output, I am still encountering the error message Not all code paths return a value I attempted removing my database calls and only leaving ...

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

What is the best way to store a logged-in user's email in a React

I have implemented a login API and I would like to save the email of the logged-in user in the state or another variable, so that I can display it in the header after successful login. The user's email is located in the data.email. The following code ...

Securing routes in Angular2 using authguards

Currently, I am working on developing a web application and facing some difficulties with routes. I have created an AuthGuard to determine if a user is logged in or not. However, the issue arises when I try to categorize routes into two types: - Routes th ...