单击表标题时对数组进行排序

时间:2019-04-15 11:11:26

标签: javascript angular typescript

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

这是我正在使用的代码

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网格上。

3 个答案:

答案 0 :(得分:1)

存储排序状态,然后根据最后的排序对asc或desc进行排序。

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' } ]

答案 1 :(得分:0)

  

尝试一下,希望对您有帮助

// asc
this.dataArray.sort(function(a, b){
    if(a.lastName.toString().toLowerCase() < b.lastName.toString().toLowerCase()) { return -1; }
    if(a.lastName.toString().toLowerCase() > b.lastName.toString().toLowerCase()) { return 1; }
});
// des
this.dataArray.sort(function(a, b){
    if(b.lastName.toString().toLowerCase() < a.lastName.toString().toLowerCase()) { return -1; }
    if(b.lastName.toString().toLowerCase() > a.lastName.toString().toLowerCase()) { return 1; }
}

答案 2 :(得分:0)

sorting(arr, ascending) {    
    if (typeof (ascending) === "undefined")
      ascending = true;
    var multi = ascending ? 1 : -1;
    var sorter = function (a: { lastName: string; }, b: { lastName: string; }) {
      if (a.lastName === b.lastName)      // identical? return 0
        return 0;
      else if (a.lastName === 0)  // a is null? last 
        return 1;
      else if (b.lastName === 0)  // b is null? last
        return -1;
      else                  // compare, negate if descending
        return a.lastName.toString().localeCompare(b.lastName.toString()) * multi;
    }
    return arr.sort(sorter);
  }

使用此功能,例如 this.sorting(array[],false); //对于asc为true,对于desc为false