美文网首页
在table中的前端排序

在table中的前端排序

作者: 冰凉ming | 来源:发表于2020-04-07 11:22 被阅读0次

    有些时候需要前端进行来排序,排序的时候通常需要对同时包含:数字、字母、中文的对象进行排序;

    let data = [

        {name: ‘张三’,age: 12},

        {name: ‘张三’,age: 12}

    ]

    data.sort( // 第一种方式

       (a, b) => this.sortDevName(a['name'], b['name'])

    );

    data.sort( // 第二种方式 - 仅支持中文

       (a, b) =>  return a['name'].localeCompare(b['name']);

    );

    (1)第一种方式

    在methods中定义:

    排序顺序为:数字(0->9)->大写字母(A->Z)->小写字母(a->z)->中文拼音(a->z)

        sortDevName(str1, str2) {

          let res = 0;

          for (let i = 0; ;i += 1) {

            if (!str1[i] || !str2[i]) {

              res = str1.length - str2.length;

              break;

            }

            const char1 = str1[i];

            const char1Type = this.getChartType(char1);

            const char2 = str2[i];

            const char2Type = this.getChartType(char2); // 类型相同的逐个比较字符

            if (char1Type[0] === char2Type[0]) {

              if (char1 === char2) {

                break;

              }

              if (char1Type[0] === 'zh') {

                res = char1.localeCompare(char2);

              } else if (char1Type[0] === 'en') {

                res = char1.charCodeAt(0) - char2.charCodeAt(0);

              } else {

                res = char1 - char2;

              }

              break;

            } else { // 类型不同的,直接用返回的数字相减

              res = char1Type[1] - char2Type[1];

              break;

            }

          }

          return res;

        },

        getChartType(char) {

          // 数字可按照排序的要求进行自定义,我这边产品的要求是

          // 数字(0->9)->大写字母(A->Z)->小写字母(a->z)->中文拼音(a->z)

          if (/^[\u4e00-\u9fa5]$/.test(char)) {

            return ['zh', 300];

          }

          if (/^[a-zA-Z]$/.test(char)) {

            return ['en', 200];

          }

          if (/^[0-9]$/.test(char)) {

            return ['number', 100];

          }

          return ['others', 999];

        },

    (2)第二种方式

    localeCompare() 方法来实现中文按照拼音排序,貌似仅仅支持中文排序。

    把 < 和 > 运算符应用到字符串时,它们只用字符的 Unicode 编码比较字符串,而不考虑当地的排序规则。以这种方法生成的顺序不一定是正确的

    相关文章

      网友评论

          本文标题:在table中的前端排序

          本文链接:https://www.haomeiwen.com/subject/zsegphtx.html