繁体   English   中英

typeScript如何将数组排序为数组

[英]typeScript how to sort an array into an array

我有一堂课

export class TestClass {
    id: number;
    text1: string;
    test2: string;
    text3: string;

还有另一个

export class testClassRow {
    editable: boolean;
    testClass : TestClass ;
}

在我的代码中,我有一个数组,其中填充了一些数据,因此

x:testClassRow[]; 

我想对我的x进行排序,排序键为text1。

我写了一个可以进行排序的方法,但是它不起作用,这是我的方法:

    sort(key, data) {

    if (this.key === key) {
        this.direction = this.direction * -1;
    } else {
        this.direction = 1;
    }

    this.key = key;
    data.applicationLink.sort((a, b) => {
        console.log('avlu' + a[key]);
        if (a[key] === b[key]) {
            return 0;
        }
        else if (a[key] > b[key]) {
            return 1 * this.direction;
        } else {
            return -1 * this.direction;
        }
    });

键的值为text1例如

我找到了解决方案

对sort方法的调用必须是

  this._sorter.sort(key, this.testClassRow, o => o.testClass);

排序方法是

sort(key: string, data: any[], propertyRetriever: Function) {

    if (this.key === key) {
        this.direction = this.direction * -1;
    } else {
        this.direction = 1;
    }

    this.key = key;
    data.sort((a, b) => {
        if (propertyRetriever) {
            a = propertyRetriever(a);
            b = propertyRetriever(b);
        }
        else {
            a = a;
            b = b;
        }
        if (a[key] === b[key]) {
            return 0;
        }
        else if (a[key] > b[key]) {
            return 1 * this.direction;
        } else {
            return -1 * this.direction;
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM