【问题标题】:How to sort an arraylist by multiple fields in Typescript如何在 Typescript 中按多个字段对数组列表进行排序
【发布时间】:2016-08-26 22:23:54
【问题描述】:

如何在 Typescript 中按多个字段对数组列表进行排序。

例如,我有这个对象: enter image description here

我的单一排序方法工作正常:

private sortFunction(a: RSFolderObject, b: RSFolderObject) {
    var a_label = a.label.toLowerCase();
    var b_label = b.label.toLowerCase();

    if (a_label < b_label) {
        return -1;
    } else if (a_label > b_label) {
        return 1;
    } else {
        return 0;
    }
}

对于多重排序,我使用了:

private sortFunction(a: RSFolderObject, b: RSFolderObject) {
    var a_label = a.label.toLowerCase();
    var b_label = b.label.toLowerCase();
    var a_description = a.description[0].toLowerCase().replace("\\", "");
    var b_description = b.description[0].toLowerCase().replace("\\", "");

    if (a_label < b_label || a_description < b_description) {
        return -1;
    } else if (a_label > b_label || a_description > b_description) {
        return 1;
    } else {
        return 0;
    }
}

但它不起作用。

【问题讨论】:

  • 你到底是怎么排序的?你在排序什么?你在这里展示的只是比较函数,但你用它做什么呢?另外,您能否详细说明什么不起作用?
  • 我有一个对象“RSFolderObject”。您可以在链接中看到上面的图像。这就是我要排序的对象。 1) var myObject: RSFolderObject[] = []; 2).....比将现有对象推送到 myObject..... 3) myObject.sort(this.sortFunction);

标签: arrays list sorting typescript


【解决方案1】:

好的,我是这样解决的:

private sortFunction(a: RSFolderObject, b: RSFolderObject) {

    var a_label = a.label.toLowerCase();
    var b_label = b.label.toLowerCase();
    var a_description = a.description[0].toLowerCase().replace("\\", "");
    var b_description = b.description[0].toLowerCase().replace("\\", "");

        if (a_label < b_label) {
                return -1;
            }
        else if (a_label > b_label) {
            return 1;
        }
        else {
            if (a_description < b_description) {
                return -1;
            }
            else if (a_description > b_description) {
                return 1;
            }
            else {
                return 0;
            }
        }
} 

【讨论】:

  • 看看w3schools.com/jsref/jsref_localecompare.asp,因为 localeCompare 应该消除大部分代码(返回 str1.localeCompare(str2))。此外,带有 /i 选项的 string.match 可能更适合不区分大小写的测试。
猜你喜欢
  • 2019-06-28
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
相关资源
最近更新 更多