[算法] 国家地区数组按照中文首字母排序

安装   js-pinyin

安装   underscore.js

 // 分组排序
    groupBySort(list) {
      const groupObj = _.groupBy(list, function(item) { return String(pinyin.getFullChars(item.countryName)).slice(0, 1) })
      let listNew = []
      for (let i = 65; i <= 90; i++) {
        const arr = groupObj[ String.fromCharCode(i)]
        if (arr) {
          listNew = listNew.concat(this.groupBySort2(arr, 1, 2))
        }
      }
      return listNew
    },
    groupBySort2(list, index1, index2) {
      const groupObj = _.groupBy(list, function(item) {
        return String(pinyin.getFullChars(item.countryName)).slice(index1, index2)
      })
      let listNew = []
      // 先装大写
      for (let i = 65; i <= 90; i++) {
        const arr = groupObj[ String.fromCharCode(i)]
        if (arr) {
          listNew = listNew.concat(arr)
        }
      }
      // 再装小写
      for (let i = 97; i <= 122; i++) {
        const arr = groupObj[ String.fromCharCode(i)]
        if (arr) {
          listNew = listNew.concat(this.groupBySort2(arr, index1 + 1, index2 + 1))
        }
      }
      return listNew
    },

 

posted @ 2022-02-16 12:17  coffeemil  阅读(72)  评论(0编辑  收藏  举报