0

Is there an alternative way to sort a JSON file or at least, a drop-down list other than this following code?

json.sort(function(a, b){
    return a.id - b.id;
});

The reason for this is that it takes so long to sort the JSON file containing all the countries in the world. Here is my code:

parseJSONFile("json/Country.json", function(data) {
            data.sort(sortCountryName);
            localStorage.setItem("country", JSON.stringify(data)); 
        });

// Function for sorting Countries
function sortCountryName(a,b){ 
    return a.spanish.toLowerCase() > b.spanish.toLowerCase() ? 1 : -1;
}

**Update: Here is a small part of the JSON file:

{
    "code" : "Please Select Country",
    "english" : "-- Please Select Country --",
    "spanish" : "-- Por favor seleccione el pa&#237s --"
},
{
    "code" : "AFG",
    "english" : "Afghanistan",
    "spanish" : "Afganist&#225n"
},
{
    "code" : "ALB",
    "english" : "Albania",
    "spanish" : "Albania"
},
{
    "code" : "DZA",
    "english" : "Algeria",
    "spanish" : "Argelia"
},
{
    "code" : "ASM",
    "english" : "American Samoa",
    "spanish" : "Samoa Americana"
},
7
  • 2
    Why don't you store the sorted data in the JSON file? Commented Jun 3, 2014 at 3:44
  • If what @undefined says is not viable, consider precalculating .spanish.toLowerCase() and storing it as a field in data items so you don't duplicate the effort (O(N) invocations vs up to O(N^2) invocations, depending on the underlying algorithm and structure) Commented Jun 3, 2014 at 3:46
  • actually @undefined I'm storing it in local storage after sorting, but my problem is it takes about 2 seconds long to sort the JSON file. I will update my code to include the local storing. Commented Jun 3, 2014 at 4:05
  • Do you have control over the JSON file? Can you modify it? If so perhaps provide a small sample of how the data is formatted and you may be able to optimise there. Commented Jun 3, 2014 at 4:08
  • @Amadan, thank but I didn't fully understand what you're saying, are you saying if I make my texts lowercase as default then I will not be forced to use toLowerCase() function which in turn would make the sorting much quicker? Commented Jun 3, 2014 at 4:09

2 Answers 2

3

If you can modify the JSON, then just make it sorted in the first place as @undefined said, so that the user downloads an already sorted array. If you can't, then precalculate the sort field so the number of calculations is reduced:

var header = data.shift();
data.forEach(function(item) { item.sortkey = item.spanish.toLowerCase(); });
data.sort(function(a, b) {
  var aa = a.sortkey;
  var bb = b.sortkey;
  if (aa == bb) return 0;
  return (aa < bb) ? -1 : 1;
});
data.unshift(header);

Also, make sure the two seconds are really the sorting delay and not the loading delay. There's not much you can do about the loading delay apart from processing the data serverside to reduce the memory footprint (e.g. compressing for transport, pruning to only the specified UI language...)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I will try this method now and update you as soon as I get the results. About the delay, I tried removing the sorting and it loaded instantly. By the way, I am using developing for iOS and Android devices using Phonegap.
Great! It worked like a charm. It made the sorting process to complete less than a second.
Actually I found out that the problem making the sorting take 2 seconds to complete is not with the sorting but with the console.log. I didn't know that console.log affects the performance of the app. The problem is I put a console.log("Sorting Countries...") inside the function sortCountryName() and it is being logged every time an object is sorted. You can imagine that with 50+ objects (countries), So what I did is I remove it and it's ok now.. My question is looking for an alternative and @Amadan provided it, so this is the answer.
Ouch :) Yup, I can imagine. (And I did think it was strange that you had so many thousands of countries :p)
0

This involves a bit of grunt work upfront to modify the JASON file and will make the load of the JSON file longer as it will now be bigger, but it should increase sort performance. Add a few more properties, including a sort index as an integer. I don't envy adding the sort indexes manually and then maintain them, but if the file is generated from a database it shouldn't be too bad.

Your JSON could look like the following, taking wild guesses at sort order:

{
    "code" : "Please Select Country",
    "english" : {"name" : "-- Please Select Country --", "sortIndex" : 0},
    "spanish" : {"name" : "-- Por favor seleccione el pa&#237s --" : "sortIndex" : 0}
},
{
    "code" : "AFG",
    "english" : {"name":  "Afghanistan", "sortIndex" : 1},
    "spanish" : {"name":  "Afganist&#225n", "sortIndex": 1}
},
{
    "code" : "ALB",
    "english" : {"name" : "Albania", "sortIndex" : 2},
    "spanish" : {"name" : "Albania", "sortIndex" : 2}
},
{
    "code" : "DZA",
    "english" : {"name" : "Algeria", "sortIndex": 3},
    "spanish" : {"name" : "Argelia", "sortIndex" : 4}
},
{
    "code" : "ASM",
    "english" : {"name" : "American Samoa", "sortIndex": 4},
    "spanish" : {"name" : "Samoa Americana", "sortIndex": 68}
},

With your sort function

// Function for sorting Countries
function sortCountryName(a,b){ 
    return a.spanish.sortIndex - b.spanish.sortIndex;
}

Of course another option is to have a JSON file for each language, pre-sorted and dynamilcaly load the required file. This could be a maintenacne nightmare, having to manage multiple language files.

2 Comments

Thank you for this alternative method, I appreciate the effort. This method really involves grunt work but is not practical, maybe for last resorts.
If you're getting the performance you need out of @Amadans answer, use that. Don't over optimise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.