首页 > 解决方案 > 单击表格标题对数组进行排序

问题描述

我想在单击表格标题时自动以两种方式(升序和降序)对数组进行排序

这是我正在使用的代码

SortLast() {
    this.students.sort(function (a, b) {
      var textA = a.lastName.toUpperCase();
      var textB = b.lastName.toUpperCase();
      if (textA < textB)
        return -1
      else if (textA > textB)
        return 1
      else
        return 0;
    });
  }

所以我不想指定排序顺序,它会自动以一种方式排序,上面的数组学生被修补到 HTML 上的网格。

标签: javascriptangulartypescript

解决方案


存储排序状态,然后根据最后的排序按升序或降序排序。

ASC = "asc"
DESC = "desc"

class Table {

    constructor(){
        this.sortDir = null;
        this.students = [{lastName: "John"}, {lastName: "Zoe"}, {lastName: "Ana"}];
    }

    isAsc(){ return this.sortDir === ASC; }
    isDesc(){ return this.sortDir === DESC; }

    sort() {
        const scope = this;
        this.sortDir = this.isAsc() ? DESC: ASC

        this.students.sort(function (a, b) {
            const textA = scope.isDesc() ? b.lastName.toUpperCase() :  a.lastName.toUpperCase();
            const textB = scope.isDesc() ?  a.lastName.toUpperCase() :  b.lastName.toUpperCase();
            return  (textA < textB) ? -1 : (textA > textB) ? 1 : 0
        });
    }
}

尝试:

const table = new Table()
console.log(table.sortDir,table.students)
table.sort()
console.log(table.sortDir, table.students)
table.sort()
console.log(table.sortDir, table.students)

输出:

null [ { lastName: 'John' }, { lastName: 'Zoe' }, { lastName: 'Ana' } ]
asc [ { lastName: 'Ana' }, { lastName: 'John' }, { lastName: 'Zoe' } ]
desc [ { lastName: 'Zoe' }, { lastName: 'John' }, { lastName: 'Ana' } ]

推荐阅读