【问题标题】:Sort javascript object on multiple keys order by alphabet按字母顺序对多个键排序 javascript 对象
【发布时间】:2015-08-25 15:25:36
【问题描述】:

这是我的 js 对象:

var data = [
    { id: 7, name: "test1", sector: "A01" },
    { id: 7, name: "test2", sector: "C03" },
    { id: 8, name: "test4", sector: "B02" },
    { id: 8, name: "test5", sector: "A01" },
    { id: 8, name: "test6", sector: "C03" },
    { id: 7, name: "test3", sector: "B02" },
];

我想按 id 然后按扇区对这个对象进行排序,如下所示:

7,test1,A01
7,test3,B02
7,test2,C03
8,test5,A01
8,test4,B02
8,test6,C03

我试过thenBy.js,代码是here,结果是

7,test1,A01
7,test2,C03
7,test3,B02
8,test4,B02
8,test5,A01
8,test6,C03

如何解决?

如果看不到输出,请转到左侧面板上的外部资源并为 Firebug 添加以下链接:getfirebug.com/firebug-lite-debug.js

【问题讨论】:

  • @RobertStettler 我在我的代码中使用了它,在第二行列出。

标签: javascript jquery sorting jquery-ui-sortable


【解决方案1】:

我看过你的小提琴,你正在尝试减去字符串,这将导致NaNs,它不能真正用于排序。

如果您在比较字符串时尝试使用><,它会起作用。

例子:

firstBy(function (v1, v2) { return v1.id < v2.id ? -1 : (v1.id > v2.id ? 1 : 0); })
  .thenBy(function (v1, v2) { return v1.sector > v2.sector; });

这将产生您正在寻找的结果。

【讨论】:

  • 非常感谢。有用。代码是从 thenby.js 示例粘贴的,这就是我没有注意到的原因。
【解决方案2】:

您可以在没有firstBy().thenBy 构造的情况下通过简单地连接字符串来做到这一点。 sort 函数的参数如下所示:

function (v1, v2) { return v1.id + v1.sector < v2.id + v2.sector ? -1 : (v1.id + v1.sector> v2.id + v2.sector ? 1 : 0); }

这里是fixed fiddle

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 2019-07-18
    • 1970-01-01
    • 2023-01-30
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多