0

how can I rewrite this code so that it can sort not only from A-Z, but also back, using just one button. Here is my code, but it does not work correctly.It is sorted only from A-Z, and in the opposite direction does not want.

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  
}`enter code here`

html:

<a class="sort" (click)="sortType('name')" [class.active]="sortBy === 'name'" >name</a>
2
  • Just to avoid unecessary repeat of code, I would suggest your second sort to call the first one ; sortByCountryName1(c1, c2) { this.sortByCountryName(c2, c1); } . Also you could rename it with "reverse" instead of "1" at the end. Commented Jan 25, 2018 at 3:41
  • Just a reminder that Angular uses TypeScript, and you can take advatage of any JS with it Commented Jan 25, 2018 at 4:13

1 Answer 1

1

use sort((c1: SprBitType, c2:SprBitType) => c1.name - c2.name) for ascending and

sort((c1: SprBitType, c2:SprBitType) => c2.name - c1.name) for descending.

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)
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.