Yumi
Yumi

Reputation: 35

Sorting in Angular2

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>

Upvotes: 0

Views: 48

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

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

}

Upvotes: 1

Related Questions