tomatito
tomatito

Reputation: 411

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!

Upvotes: 3

Views: 1070

Answers (2)

Yuci
Yuci

Reputation: 30189

You can try using method Array.prototype.sort() instead of filter:

<template>
    <div></div>
</template>

<script>
let countries = require("country-data").countries;

export default {
mounted() {
    let sortedCountries = countries.all
    .sort((c1, c2) => {
        if (c1.name < c2.name) return -1;
        if (c1.name > c2.name) return 1;
        return 0;
    })
    .map(country => {
        return {
            name: country.name,
            alpha3: country.alpha3
        };
    });

    console.log("sortedCountries: ", sortedCountries);
  }
};
</script>

<style scoped>
</style>

And you will see the output sorted by country names alphabetically as shown below:

enter image description here

Updated:

Probably better you should use String.prototype.localeCompare(compareString[, locales[, options]]), and the locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function.

<script>
let countries = require("country-data").countries;

export default {
mounted() {
    let sortedCountries = countries.all
    .sort((c1, c2) => c1.name.localeCompare(c2.name))
    .map(country => {
        return {
            name: country.name,
            alpha3: country.alpha3
        };
    });

    console.log("sortedCountries: ", sortedCountries);
  }
};
</script>

And you'll get a slightly different list:

enter image description here

Upvotes: 2

gyc
gyc

Reputation: 4360

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
  }));
}

Upvotes: 4

Related Questions