代码之家  ›  专栏  ›  技术社区  ›  LAffair

Javascript自然排序对象

  •  2
  • LAffair  · 技术社区  · 8 年前

    array[0] = {id: 1, name: "First"}
    array[1] = {id: 2, name: "Second"}
    

    我试着把它分类 name 字段使用:

    Array.prototype.alphanumSort = function (caseInsensitive) {
    for (var z = 0, t; t = ((typeof this[z] == "string" || typeof this[z] == "undefined") ? this[z] : this[z].name); z++) {
        this[z] = new Array();
        var x = 0, y = -1, n = 0, i, j;
    
        while (i = (j = t.charAt(x++)).charCodeAt(0)) {
            var m = (i == 46 || (i >= 48 && i <= 57));
            if (m !== n) {
                this[z][++y] = "";
                n = m;
            }
            this[z][y] += j;
        }
    }
    
    this.sort(function (a, b) {
        for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
            if (caseInsensitive) {
                aa = aa.toLowerCase();
                bb = bb.toLowerCase();
            }
            if (aa !== bb) {
                var c = Number(aa), d = Number(bb);
                if (c == aa && d == bb) {
                    return c - d;
                } else return (aa > bb) ? 1 : -1;
            }
        }
        return a.length - b.length;
    });
    
    for (var z = 0; z < this.length; z++)
        this[z] = this[z].join("");
    }
    

    但是我从中得到的列表包含一个数组 字段,没有相应的 id 我是JavaScript新手,所以请温柔一点。

    4 回复  |  直到 8 年前
        1
  •  4
  •   Community Mohan Dere    6 年前

    你可以用 sorting with map 和 String#localeCompare options

    敏感

    字符串中的哪些差异应导致非零结果值。可能的值为:

    • "base" a ≠ b , a = á a = A .
    • "accent" :只有在基音、重音和其他音调符号上不同的字符串才会比较为不相等。示例: a和b a ≠ á , a=a
    • "case" :只有基字母或大小写不同的字符串比较为不相等。示例: a和b , a= , a ≠ A .
    • "variant" a和b 一 , .

    数字

    是否应使用数字排序规则,例如“1”<2英寸<10". 可能的值为 true 和 false ; 默认值为 . 可以通过options属性或Unicode扩展键设置此选项;如果两者都提供,则

    var array = ['Ex 10', 'Ex 2', 'a 10.1', 'a 1.1', 'a 10.0', 'a 2.0'];
    
    array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));
    
    console.log(array)
        2
  •  1
  •   PR7    7 年前

    你可以用 String.prototype.localeCompare

    var arr = [
        {id: 1, name: "Third"},
        {id: 2, name: "Fifth"},
        {id: 3, name: "Second"},
        {id: 4, name: "Fourth"},
        {id: 5, name: "First"}
    ];
    
    arr.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }));
    
    console.log(arr);
    
        3
  •  0
  •   Dan Stanciu    8 年前

    https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js ):

    array[0] = {id: 1, name: "First"}
    array[1] = {id: 2, name: "Second"}
    array = _.orderBy(array, 'name', 'desc')