按字母顺序排序 JSON(按特定元素)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19259233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:52:46  来源:igfitidea点击:

Sorting JSON (by specific element) alphabetically

javascriptjsonsorting

提问by Alex Neigher

I have some JSON that is formatted like:

我有一些 JSON 格式如下:

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

et cetera...

等等...

I am trying to sort this alphabetically BY CITYand am having trouble doing so. I believe the root of my issue seems to be determining the order of the characters (versus numbers). I've tried a simple:

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

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

yet, this subtraction doesnt know what to do. Can someone help me out?

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

回答by Matti Virkkunen

Unfortunately there is no generic "compare" function in JavaScript to return a suitable value for sort(). I'd write a compareStrings function that uses comparison operators and then use it in the sort function.

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

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);
})

回答by Michael Geary

Matti's solution is correct, but you can write it more simply. You don't need the extra function call; you can put the logic directly in the sortcallback.

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

For case-insensitive sorting:

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

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

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

For case-sensitive sorting:

对于区分大小写的排序:

places.sort( function( a, b ) {
    return a.city < b.city ? -1 : a.city > b.city ? 1 : 0;
});