Home > Net >  Make one function instead of many to sort by column
Make one function instead of many to sort by column

Time:12-01

I would like to know how to make only one function to sort my array's columns. Currently I have many function like this for each column:

  sort() {
    if (this.sortAsc == false) {
      this.tab.sort((a, b) => {
        return a.name.localeCompare(b.name);
      });
      this.sortAsc = true;
    } else {
      this.tab.sort((a, b) => {
        }
        return b.name.localeCompare(a.name);
      });
      this.sortAsc = false;
    }
  }

A piece of the table:

         ...
          <tr>
              <th (click)="sort()">Name</th>
              ...
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let item of tab" (click)="getById(item.id)" tabindex="0">
            <td> {{ item.name }} </td>
            ...
          </tr>
         ...

CodePudding user response:

You could add a parameter to sort such as the name of the variable you want to sort by: sort('name') In the sort function you could then use that parameter to differentiate what you want to sort.

sort(val: string) {
    if(!this.sortAsc) {
        this.tab.sort((a,b) => {
            return a[val].localeCompare(b[val]);
        });
        this.sortAsc = true;
    }
    ...
}
  • Related