14

我有一些 JSON 格式如下:

places =[
     {
      "city":"Los Angeles",
      "country":"USA",
     },
     {
      "city":"Boston",
      "country":"USA",
     },
     {
      "city":"Chicago",
      "country":"USA",
     },
] 

等等...

我正在尝试按城市的字母顺序对此进行排序,但 在这样做时遇到了麻烦。我相信我的问题的根源似乎是确定字符的顺序(相对于数字)。我试过一个简单的:

    places.sort(function(a,b) {
     return(a.city) - (b.customInfo.city);
    });

然而,这个减法不知道该怎么做。有人可以帮我吗?

4

2 回答 2

41

不幸的是,JavaScript 中没有通用的“比较”函数来为 sort() 返回合适的值。我会编写一个使用比较运算符的 compareStrings 函数,然后在 sort 函数中使用它。

function compareStrings(a, b) {
  // Assuming you want case-insensitive comparison
  a = a.toLowerCase();
  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

places.sort(function(a, b) {
  return compareStrings(a.city, b.city);
})
于 2013-10-08T22:01:20.030 回答
16

Matti 的解决方案是正确的,但你可以写得更简单。您不需要额外的函数调用;您可以将逻辑直接放在sort回调中。

对于不区分大小写的排序:

places.sort( function( a, b ) {
    a = a.city.toLowerCase();
    b = b.city.toLowerCase();

    return a < b ? -1 : a > b ? 1 : 0;
});

对于区分大小写的排序:

places.sort( function( a, b ) {
    return a.city < b.city ? -1 : a.city > b.city ? 1 : 0;
});
于 2013-10-08T22:26:24.467 回答