Sort Array Elements (string with numbers), natural sort

后端 未结 8 1075
你的背包
你的背包 2020-11-22 10:15

I have an array like;

[\"IL0 Foo\", \"PI0 Bar\", \"IL10 Baz\", \"IL3 Bob says hello\"]

And need to sort it so it appears like;



        
8条回答
  •  执念已碎
    2020-11-22 10:32

    Not pretty, but check the first two char codes. If all equal parse and compare the numbers:

    var arr = ["IL0 Foo", "IL10 Baz", "IL3 Bob says hello", "PI0 Bar"];
    arr.sort(function (a1, b1) {
        var a = parseInt(a1.match(/\d+/g)[0], 10),
            b = parseInt(b1.match(/\d+/g)[0], 10),
            letterA = a1.charCodeAt(0),
            letterB = b1.charCodeAt(0),
            letterA1 = a1.charCodeAt(1),
            letterB1 = b1.charCodeAt(1);
        if (letterA > letterB) {
            return 1;
        } else if (letterB > letterA) {
            return -1;
        } else {
            if (letterA1 > letterB1) {
                return 1;
            } else if (letterB1 > letterA1) {
                return -1;
            }
            if (a < b) return -1;
            if (a > b) return 1;
            return 0;
        }
    });
    

    Example

提交回复
热议问题