簡體   English   中英

過濾后如何按字母順序排列字符串數組?

[英]How to order an array of strings alphabetically after filter?

我正在我的 VUE 應用程序中查看一個數組,它具有以下結構

[
{
  "id": 1,
  "brands": [
    {
      "name": "Mall",
      "id": 1
    },
    {
      "name": "Tanted",
      "id": 25
    },
    {
      "name": "Anteil",
      "id": 12
    },
    {
      "name": "Moscard",
      "id": 73
    }
  ]
},
{
  "id": 2,
  "brands": [
    {
      "name": "Yanre",
      "id": 6
    },
    {
      "name": "Alted",
      "id": 10
    },
    {
      "name": "Sillex",
      "id": 9
    },
    {
      "name": "Straf",
      "id": 78
    }
  ]
}
]

為了顯示選擇的不同選項,我要做的第一件事是按 id 過濾

computed: {
    filteredBrand() {
      var selectedBrand =
        !this.businessInfo || this.businessInfo.selectedBrand == 0
          ? 1
          : this.businessInfo.selectedBrand;
      return !this.$store.getters.brands
        ? null
        : this.$store.getters.brands.filter(
            item => item.id == selectedBrand
          )[0].brands;
    }
}


              <select
              v-model="businessInfo.selectedBrand"
              @change="onChangeBrand($event)">
              <option v-for="brand in filteredBrand" v-bind:key="brand.name">{{ brand.name }}</option>
              </select>


到目前為止,我設法顯示了與選擇中每個 id 相對應的品牌,但我也想按字母順序對它們進行排序,但我找不到將過濾器與排序相結合的方法。 我試圖連接這些方法,但它返回一個語法錯誤。

computed: {
    filteredBrand() {
      var selectedBrand =
        !this.businessInfo || this.businessInfo.selectedBrand == 0
          ? 1
          : this.businessInfo.selectedBrand;
      return !this.$store.getters.brands
        ? null
        : this.$store.getters.brands.filter(
            item => item.id == selectedBrand
          )[0].brands.sort(function(a, b) {
      return a.name === b.name ? 0 : +(a.name > b.name) || -1;
    });
    }
}


我該怎么做? 提前感謝大家的時間和幫助

要按字典順序(松散地,按字母順序)按升序 (AZ) 比較兩個字符串,您可以在sort回調中執行此操作:

return a.name.localeCompare(b.name);

對於降序 (ZA),請使用

return b.name.localeCompare(a.name);

旁注:任何時候你發現自己在寫array.filter(/*...*/)[0] ,改寫array.find(/*...*/) (Polyfilling find如果您需要 IE 支持。) find方法在找到第一個匹配條目並返回該條目時停止,而不是遍歷整個數組,從所有匹配條目構建一個新數組。 如果您只想獲取第一個條目,則無需遍歷整個數組並構建一個新數組。 :-)

因此,將其與上面的主要答案結合起來:

  return !this.$store.getters.brands
    ? null
    : this.$store.getters.brands.find(
        item => item.id == selectedBrand
      ).brands.sort((a, b) => a.name.localeCompare(b.name));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM