Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have some JSON that is formatted like:

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

et cetera...

I am trying to sort this alphabetically BY CITY and 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
300 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...