Sorting JSON (by specific element) alphabetically

后端 未结 2 1333
慢半拍i
慢半拍i 2020-12-14 23:22

I have some JSON that is formatted like:

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


        
相关标签:
2条回答
  • 2020-12-15 00:02

    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.

    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);
    })
    
    0 讨论(0)
  • 2020-12-15 00:05

    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 sort callback.

    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;
    });
    
    0 讨论(0)
提交回复
热议问题