Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting JSON (by specific element) alphabetically

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?

like image 680
Alex Neigher Avatar asked Oct 08 '13 21:10

Alex Neigher


People also ask

How do I sort JSON elements?

One option might be to make your data look like this: var json = [{ "name": "user1", "id": 3 }, { "name": "user2", "id": 6 }, { "name": "user3", "id": 1 }]; Now you have an array of objects, and we can sort it. Show activity on this post.

Is JSON in alphabetical order?

The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.

How do I sort a JSON key?

Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works. The result will automatically sort and display in the output text area.


1 Answers

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);
})
like image 93
Matti Virkkunen Avatar answered Sep 19 '22 09:09

Matti Virkkunen