Sort JSON (by specific element) in alphabetical order

I have JSON that is formatted like this:

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

et cetera ...

I am trying to sort this alphabetically BY BY CITY and I am having problems with this. I believe that the root of my problem seems to determine the character order (compared to numbers). I tried just:

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

this subtraction does not know what to do. Can someone help me?

+6
source share
2 answers

Unfortunately, JavaScript does not have a general β€œcompare” function to return a suitable value for sort (). I would write a compareStrings function that uses comparison operators, and then use it in a 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); }) 
+21
source

Matti's solution is correct, but you can write it more simply. You do not need an additional 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; }); 
+4
source

Source: https://habr.com/ru/post/955537/


All Articles