Jody Sergison
Jody Sergison

Reputation: 45

Sort and print JSON output alphabetically in Javascript

I have a function that pulls a list of countries from a JSON array

function regionPlanOutput(networkGroupId) {
    document.getElementById("country_list").innerHTML = "";
    jQuery.ajax({
        type: 'GET'
        , url: regionApiURL + '/api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
        , dataType: 'json'
        , success: function (networkGroup) {
            jQuery.each(networkGroup.countryList, function (i, countryList) {
                var countryName = countryList.name;
                var flag = countryList.logoUrl;
                var countrycontent = '<li>' + countryName + '</li>';
                console.log(countrycontent)
                jQuery(countrycontent).appendTo("#country_list");
            });
        }
    });
}

At the moment it just prints the list in the order it pulls them from the array, How do I sort the output alphabetically based on the variable countryName?

Upvotes: 1

Views: 1140

Answers (4)

cнŝdk
cнŝdk

Reputation: 32145

In your success function networkGroup is already a JavaScript object and not a JSON object.

So you just need to use Array.prototype.sort() method with your networkGroup.countryList array to get the sorted array.

This is how should be your code:

success: function(networkGroup) {
  networkGroup.countryList = networkGroup.countryList.sort(function(a, b) {
    var nameA = a.countryName.toUpperCase();
    var nameB = b.countryName.toUpperCase();
    if (nameA < nameB) {
      return -1;
    }
    if (nameA > nameB) {
      return 1;
    }
    return 0;
  });
  //The rest of your code 
}

Demo:

This is a working Demo snippet:

var group = {
  countryList: [{
      countryName: "Vietnam",
      prop: "5224"
    },
    {
      countryName: "USA",
      prop: "000"
    },
    {
      countryName: "Palestine",
      prop: "5454"
    },
    {
      countryName: "Nigeria",
      prop: "1717"
    },
    {
      countryName: "Albania",
      prop: "54"
    },
    {
      countryName: "Belgium",
      prop: "1000"
    }
  ]
};



var sortArray = function sortArray(networkGroup) {
  networkGroup.countryList = networkGroup.countryList.sort(function(a, b) {
    var nameA = a.countryName.toUpperCase();
    var nameB = b.countryName.toUpperCase();
    if (nameA < nameB) {
      return -1;
    }
    if (nameA > nameB) {
      return 1;
    }
    return 0;
  });
  return networkGroup.countryList;
}
console.log(sortArray(group));

Upvotes: 0

Mark
Mark

Reputation: 92440

Lets assume your networkGroup.countryList looks something like this:

countryList = [
    {name: "someName", logUrl: "http://example.com"},
    // ...etc.
]

You can sort by countryList.name like this:

countryList.sort(function(a, b){
    return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)
})

This will sort in place, so after you run that, your countryList will be changed to the sorted order. If you sort networkGroup.countryList before you call jQuery.each you should be good to go.

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21485

Instead of modifying the DOM inside the loop as you step through networkGroup.countryList (which makes sorting more complicated, and is a bad idea performance-wise anyway), capture the country names in a temporary array, sort that array, then drop it into the DOM in one go:

success: function (networkGroup) {
    var output = []; // temporary array
    jQuery.each(networkGroup.countryList, function (i, countryList) {
        output.push('<li>'+countryList.name+'</li>'); // capture each name in the temporary array.  We'll go ahead and include the <li> tags here since it won't affect the sort order
    });
    output.sort(); // sort it
    jQuery("#country_list").append(output.join('')); // drop it into the DOM
}

Upvotes: 1

Jay Lane
Jay Lane

Reputation: 1401

use the sort method on the returned array, should default to alphabetical since you're dealing with strings in the array.

Upvotes: 0

Related Questions