Organizing Data in Angular 2

I'm trying to modify this code so that it can sort both A-Z and Z-A using a single button. The current code only sorts from A-Z and doesn't work in reverse order. Here is the code I have, but it's not functioning correctly.

sortType(sort: string, order: string){
    if(sort === 'name') {
        this.projects = this.projects.sort(this.sortByCountryName)
            console.log(this.sprBitTypes);
    } 
    else {this.projects = this.projects.sort(this.sortByCountryName1);}

}


sortByCountryName(c1: SprBitType, c2:SprBitType){
    if(c1.name > c2.name)  return 1
        else if (c1.name == c2.name)return 0
    else return -1  
}
sortByCountryName1(c1: SprBitType, c2:SprBitType){
    if(c1.name < c2.name)  return 1
        else if (c1.name == c2.name)return 0
    else return -1  
}

html:

<a class="sort" (click)="sortType('name')" [class.active]="sortBy === 'name'" >name</a>

Answer №1

To sort in ascending order, use

sort((c1: SprBitType, c2:SprBitType) => c1.name - c2.name)
. For descending order, use
sort((c1: SprBitType, c2:SprBitType) => c2.name - c1.name)
.

sortType(sort: string, order: string) {
    if (sort === 'name') {
        this.projects = this.projects.sort((c1: SprBitType, c2:SprBitType) => c1.name - c2.name)
        console.log(this.sprBitTypes);
    } else {
        this.projects = this.projects.sort((c1: SprBitType, c2:SprBitType) => c2.name - c1.name)
    }
}

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

Errors in typing occurring due to preact children within framer-motion

While working on my preact widget (https://github.com/preactjs-templates/widget), I noticed a connection to ReactDOM. import { motion } from 'framer-motion'; import { h, VNode } from 'preact'; const Test = () => { return <mot ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

A custom type in Typescript used as a key in a key-value pair

Here is a key-value pair used for a filtering system. The filter can be merged with current filters or applied by resetting the previous ones. type MINE = "mine" type BOOKMARKED = "bookmarked" type TEXT_QUERY = "textQuery" typ ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

Property ngIf in Angular is not being supplied by any relevant directive within the embedded template

When attempting to use ngIf, I encountered an error with a red underline. The error message states: "Property ngIf is not provided by any applicable directive on an embedded template." I then attempted to import commonModel, but received a new error: "src ...

Exploring Vue with Typescript - leveraging components without explicit definitions

Has anyone successfully used vue-instant component as a child component before? I'm having trouble adding components without definition. Could it be related to webpack config ignoring node_modules due to lack of type declaration? Here's the code ...

The angular2-markdown module encounters errors

I am currently working on implementing a markdown editor in a form within my Angular2 project. To achieve this, I have installed the angular2-markdown module. However, I encountered an error when trying to use it, specifically: "marked" is not a function. ...

Ways to ensure TypeScript shows an error when trying to access an array index

interface ApiResponse{ data: Student[]; } interface Student { name: string; } Imagine a scenario where we receive an API response, and I am confident that it will contain the data field. However, there is a possibility that the data could be an empty ...

pnpm, vue, and vite monorepo: tackling alias path imports within a workspace package

I am in the process of creating a monorepo for UI applications that utilize shared components and styles with pnpm, typescript, vue, and vite. While attempting to streamline development and deployment using pnpm's workspace feature, I am encountering ...

The state array is rejecting the value from the other array, resulting in null data being returned

I am currently attempting to extract image URLs from an HTML file input in order to send them to the backend and upload them to Cloudinary. However, I am facing an issue where despite having the imagesArr populated with images, setting the images state is ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Accessing variables in Angular 2 using an event object

Struggling with accessing variables through an event object. Is there a way to refactor this code? I need to display annotations in my templateUrl after setting them in an event click of the map. Here's the current code snippet: import { Component, O ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

Tips for designing a navbar specific to a profile section

I am currently working on an angular application with a navigation bar composed of anchor tags. When the user logs in, I have an ngIf directive to display my profile icon with dropdown options. However, I am facing challenges in styling it correctly. I aim ...

Adding a new value to a string variable using TypeScript

Just starting out with Angular and I'm looking to capture user input from a text box with each keystroke and add it to a string variable like in Java. In my text box, I have the following setup for capturing key events: <input type="text" ...

Avoid the expansion of line decorations in Monaco editor

I am looking to create a Monaco editor line decoration that remains contained within its original position when I press enter after the decoration. For instance, in a React environment, if I set up a Monaco editor and add a line decoration using the code ...

How can I retrieve a password entered in a Material UI Textfield?

My code is functioning properly, but I would like to enhance it by adding an option for users to view the password they are typing. Is there a way to implement this feature? const [email, setEmail] = useState(''); const [password, setPassword] = ...

Refreshing a page in Angular 2 using webpack may sometimes lead to the index.html file loading without any styling or

I'm having trouble with my Angular 2 project. Every time I refresh the page or the HRM does, it redirects to index.html (or '/') without injecting the html code and webpack head-config.common.js properly. Additionally, I noticed that the web ...

Utilizing Dynamic Variables in Angular 4 Templates

Hey everyone, I recently created an Angular 4 app and developed a component called Contentholder. The Contentholder consists of HTML & CSS to display the content holder that I am utilizing. When I include <content-holder></content-holder>, ...

Next.js is displaying an error message indicating that the page cannot be properly

Building a Development Environment next.js Typescript Styled-components Steps taken to set up next.js environment yarn create next-app yarn add --dev typescript @types/react @types/node yarn add styled-components yarn add -D @types/styled-c ...