Home > Mobile >  Sorting in angular objects in an array alphabetically
Sorting in angular objects in an array alphabetically

Time:07-15

Suppose your ts code is like this:

 items: { size: number, name: string }[] = [];

 ngOnInit(): void {

 this.items = [
      {
        size: 3, name: 'Richard'
      },
      {
        size: 17, name: 'Alex'
      },
      {
        size: 10, name: 'John'
      }]
}

How can you sort alphabetically (ascending and descending order) the name property of this array when clicking on a button?

CodePudding user response:

Define two buttons that will pass asc or desc flag to a function. Execute the function to do the sorting:

html:

<button (click)="sort(true)">ASC</button>
<button (click)="sort(false)">DESC</button>

component.ts:

sort(isAsc: boolean) {
  if (isAsc) {
    this.items.sort((a, b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)
  } else {
    this.items.sort((a, b) => (a.name > b.name) ? -1 : ((b.name > a.name) ? 1 : 0)
  }
}

ASC:

enter image description here

Desc:

enter image description here

  • Related