简体   繁体   English

排序-将数字和特殊字符移到末尾

[英]Sort - Move numbers and special characters to the end

I am trying to sort an array which looks like this: 我正在尝试对看起来像这样的数组进行排序:

var arr = ["a", "c", "1", "e", "-", "4", "p", "$", "~", "6", "33", "h"];

the order I want to get should be: 我要获得的订单应为:

var arr = ["a", "c", "e", "h", "p", "-", "~", "$", "1", "33", "4", "6"];

I already have a working solution but I am not sure if this is the best (fastest) way how to do it. 我已经有一个可行的解决方案,但是我不确定这是否是最好(最快)的方法。

arr.sort(function(a, b) {
    return a.localeCompare(b);
});

for (var i = 0; i < arrLength; i++) {
    if (arr[i].localeCompare("a") >= 0) {
        if (i > 0) {
            Array.prototype.push.apply(arr, arr.splice(0, i));
        }

        break;
    }
}

Yes, you should include the logic in the comparison function. 是的,您应该在比较功能中包含逻辑。 This will be easier to understand than first sorting by one criteria and then shifting around parts of the array by some other criteria, and it will be reusable in other situations. 这比起先按一个条件进行排序然后再按其他条件在数组的各个部分之间移动要容易理解,并且在其他情况下可以重用。

You want 你要

arr.sort(function(a, b) {
    var aIsAlphabetical = a.localeCompare("a") >= 0,
        bIsAlphabetical = b.localeCompare("a") >= 0;
    if (!aIsAlphabetical && bIsAlphabetical)
        return 1;
    if (aIsAlphabetical && !bIsAlphabetical)
        return -1;
    return a.localeCompare(b);
});

or, shortened: 或缩短:

arr.sort(function(a, b) {
    return (b.localeCompare("a")>=0)-(a.localeCompare("a")>=0) || a.localeCompare(b);
});

If you're looking for fastest code, you should set up a benchmark at the targetted system with a good example array. 如果您正在寻找最快的代码,则应使用一个良好的示例数组在目标系统上设置基准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM