Sort Array Elements (string with numbers), natural sort

后端 未结 8 1076
你的背包
你的背包 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:31

    Pad numbers in string with leading zeros, then sort normally.

    var naturalSort = function (a, b) {
        a = ('' + a).replace(/(\d+)/g, function (n) { return ('0000' + n).slice(-5) });
        b = ('' + b).replace(/(\d+)/g, function (n) { return ('0000' + n).slice(-5) });
        return a.localeCompare(b);
    }
    
    var naturalSortModern = function (a, b) {
        return ('' + a).localeCompare(('' + b), 'en', { numeric: true });
    }
    
    console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSort)));
    
    console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSortModern)));

提交回复
热议问题