在javascript / vue中按名称排序国家/地区

时间:2018-04-08 09:47:39

标签: javascript vue.js vuejs2

我正在使用country-data库:

{
  "name": "apoc",
  "version": "0.1.0",
  "private": true,
  "homepage": "%REACT_APP_BASENAME%",
  "dependencies": {....

我无法在我的选择组件中按名称对国家/地区进行排序

谢谢你!

2 个答案:

答案 0 :(得分:2)

来自docs

我认为你想使用排序而不是过滤器。

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

在您的情况下,这可能有效:

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

您也可以使用localeCompare

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

答案 1 :(得分:1)

您可以尝试使用方法Array.prototype.sort()代替过滤器:

<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>

您将看到输出按字母顺序按国家/地区名称排序,如下所示:

enter image description here

<强>更新

您可能应该使用String.prototype.localeCompare(compareString[, locales[, options]]),并且locales和options参数允许应用程序指定应使用其排序顺序的语言,并自定义函数的行为。

<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>

你会得到一个略有不同的名单:

enter image description here