Combine arrays of JSON objects and sort them using Javascript

I have a JSON object with 12 arrays. Different regions of the countries. I am trying to combine this array into a dropdown menu. JSON looks like this:

"latinamerica": [ "Argentina", "Bolivia", "Brazil", "Chile", "Colombia", "Ecuador", "Paraguay", "Peru" ], "korea": ["South Korea"] 

Then I call in JSON with:

  $.getJSON('js/countries.json', function(data) { var items = []; items[0] = '<option value="0">Country</option>'; $.each(data['latinamerica'], function(key, val) { items.push('<option value="'+ key +'">'+ val +'</option>'); }); }); 

Doing this for each array in the object. The problem is that I want to combine all these arrays, sort them in alphabetical order, but at the same time save what area they are associated with. Therefore, in essence, I would have had the fall of all countries, and the HTML would have looked like this:

 <option value="latinamerica">Argentina</option> <option value="europe">Austria</option> 

I tried doing concat, but then I lose the array names. Suggestions? TIA.

+3
source share
2 answers

To create this “view” you need another “model”:

 var countries = []; for (var region in data) { for (var i = 0, l = data[region].length; i < l; ++i) { countries.push({ country: data[region][i], region: region }); } } 

Then you sort it:

 countries.sort(function(a, b) { if (a.country < b.country) return -1; if (a.country > b.country) return 1; return 0; }); 

And then you use it:

 var items = []; items.push('<option value="0">Country</option>'); for (var i = 0, l = countries.length; i < l; ++i) { items.push('<option value="'+ countries[i].region +'">'+ countries[i].country +'</option>'); } 

(NOTE: all of this code has not been verified).

+4
source
 items.sort(function(a, b) { if (a.innerHTML < b.innerHTML) return -1; else return 1; }); 

Add the Country option after sorting.

0
source

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


All Articles