0

please can you help me to populate my select list alphabetically.

Here is the code I have so far:-

$.getJSON("php/countryBorders.geo.json", (data) => {
  $select.html("");
  

  for (let i = 0; i < data["features"].length; i++) {
    
    $select.append(
      '<option value="' +
        data["features"][i]['properties']["iso_a2"] +
        '">' +
        data["features"][i]["properties"]["name"]
       
    );  
   
  }
});
freedomn-m
  • 27,664
  • 8
  • 35
  • 57

3 Answers3

0

Firstly Extract the text and value of each option tag into an array of objects. ANd sort the array. Then update the option elements with the array contents in order

var opts = $('select');
var arr = opts.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
opts.each(function(i, o) {
  o.value = arr[i].v;
  $(o).text(arr[i].t);
});
Nbody
  • 1,168
  • 7
  • 33
0

you can use below logic for sorting, you just need to use name value instead of a and b while comparing (from the the array which you want to sort).

var data  = ["ball","cat","elephant","dog","apple"];
console.log(data);
data.sort(function(a, b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});
console.log(data);
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0
$.getJSON("php/countryBorders.geo.json", (data) => {
  $select.html("");
  
  const features = data["features"].sort((a,b) => {
    return (
      (a.properties.name < b.properties.name && -1) ||
      (a.properties.name > b.properties.name && 1) ||
      0
    ); 
  });
  
  features.forEach(feature => {
    $select.append(`<option value="${feature.properties.iso_a2}">${feature.properties.name}</option>`);
  });
});
secan
  • 2,622
  • 1
  • 7
  • 24