Say I have an object that looks like this:
countrylist:{
regions:[
{
region: "Europe",
countries: [
{
"country":"Albania",
"href":"eu",
"locale":"en_al"
},
{
"country":"France",
"href":"eu",
"locale":"en_fr"
},
{
"country":"Ireland",
"href":"eu",
"locale":"en_ie"
}]
},
region: "Asia",
countries: [
{
"country":"China",
"href":"as",
"locale":"ch"
},
{
"country":"Japan",
"href":"as",
"locale":"jp"
},
{
"country":"Thailand",
"href":"as",
"locale":"th"
}]
}
]}
If you could see the whole object, you would see that it's grouped by region, and the countries within each region are sorted alphabetically. However, I need to populate a dropdown menu of all the countries, alphabetized, but not by region. What's the cleanest method to go about sorting these items?
I originally pushed the country field to an empty array and sorted that. However, I need to preserve the relationship between the country field and its corresponding href and locale fields.
Initialize an empty array, then go through the regions and append all the countries to that array. When you're done, sort the array.
var countries = [];
for(var i = 0; i < countrylist.regions.length; i++)
Array.prototype.push.apply(countries, countrylist.regions[i].countries);
countries.sort(function(a, b) {
return a.country > b.country;
});
console.log(countries);
http://jsfiddle.net/Jehsb/
You need to walk your structure and create an array of country names. You can then sort the array, and you're done.
var arr = [];
for(var i = 0; i < countryList.regions.length; i++){
var countries = countryList.regions[i].countries;
for(var j = 0; j < countries.length; j++){
arr.push(countries[j].country);
}
}
arr.sort();
If you need the other information as well, what you'd need is a flat array of all country objects, and then apply a custom sort function:
var arr = [];
for(var i = 0; i < countryList.regions.length; i++){
var countries = countryList.regions[i].countries;
for(var j = 0; j < countries.length; j++){
arr.push(countries[j]);
}
}
arr.sort(function(xx,yy){
return xx.country < yy.country ? -1 : 1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With