Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting countries by name in javascript/vue

i'm using country-data library:

loadCountries() {
  return require("country-data")
  .countries.all.filter(country => country.name)
  .map(country => ({
    label: country.name,
    value: country.alpha3
  }));
},

i'm not be able to sort countries by name in my select component

thank you!

like image 421
tomatito Avatar asked Jul 08 '26 20:07

tomatito


1 Answers

From the docs

I think you want to use sort instead of filter.

var items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 }
];
items.sort(function (a, b) {
  return a.value - b.value;
});

In your case, this may work:

loadCountries() {
  return require("country-data")
  .countries.all.sort((a, b) => a.name - b.name)
  .map(country => ({
    label: country.name,
    value: country.alpha3
  }));
}

You can also use localeCompare

loadCountries() {
  return require("country-data")
  .countries.all.sort((a, b) => a.name.localeCompare(b.name))
  .map(country => ({
    label: country.name,
    value: country.alpha3
  }));
}
like image 175
gyc Avatar answered Jul 11 '26 12:07

gyc