修剪数组条目并使用JS进行数字排序

时间:2015-07-02 19:10:22

标签: javascript regex

我有以下数组,我想将每个条目修剪为数字和一个字母,然后按数字顺序排列。

["10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long"]

我试过玩正则表达式,但发现很难

3 个答案:

答案 0 :(得分:2)

var arr = [
    "10Regular", "18Regular", "14Long", "14Regular",
    "10Long", "16Long", "12Long", "20Regular",
    "16Regular", "12Regular", "18Long"
];

var trimmedAndSorted = arr.map(function(e) {
    return e.replace(/(\d+[a-z]).*/i, '$1');
}).sort();

得到了downvote所以我假设存在语法错误,但我使用a JSFiddle and it appears to work进行了测试。

答案 1 :(得分:1)

如果您只是想使用前面的数字对它们进行排序,而不管它们之后的字母是什么,给定arr数组:

arr.map(function(entry){
  // extract the number and first letter as [number, letter]
  return entry.match(/^(\d+)(.{1})/).slice(1)
}).sort(function(a, b){
  // Sort the array by the number part 
  return +a[0] - +b[0];
}).map(function(entry){
  // Join the two parts 
  return entry.join('');
});

// ["10R", "10L", "12R", "12L", "14L", "14R", "16L", "16R", "18R", "18L", "20R"]

答案 2 :(得分:1)

定义一个排序函数,它接受增强排序的功能

我最喜欢的排序函数(比这个任务所需的更通用)可以对任何嵌套深度的值或对象的数组进行排序,并接受用于启动值的可选函数,以及用于辅助“then by”的可选函数排序

排序依据,然后按功能排序:

var by = function (path, reverse, primer, then) {

        // Light weight json deep access
    var get = function (obj, path) {
            if (path) {
                path = path.split('.');
                for (var i = 0, len = path.length - 1; i < len; i++) {
                    obj = obj[path[i]];
                };
                return obj[path[len]];
            }
            return obj;
        },

        // Invokes primer function if provided
        prime = function (obj) {
            return primer ? primer(get(obj, path)) : get(obj, path);
        };

    // Actual sorting function to be returned to native .sort method
    return function (a, b) {
        var A = prime(a),
            B = prime(b);

        return (
            (A < B) ? -1 :
            (A > B) ?  1 :
            // If A == B, then sort by supplemental 'by' function received as 'then' 
            (typeof then === 'function') ? then(a, b) : 0
        ) * [1,-1][+!!reverse];
    };
};

致谢:上面的函数是我发现的函数的一个分支,我发现它是对Stack Overflow question的回应。

基本用法:

array.sort(
    by(path[, reverse[, primer[, then]]])
);

您的阵列使用示例:

/* THE ARRAY */
var arr = ["10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long"];

/* THE EXAMPLE */
arr.sort(
    by(null, false,
        function (x) { // Primer
            var y = x.substr(0,2);
            return parseFloat(y);
        },
        by(null, false, // Secondary "then by" sort
            function (x) { // Primer
                var y = x.substr(2);
                return y;
            }
        )
    )
);

这里的想法是将您的值分成两个部分,您希望对其进行排序。

假设您的字符串值始终以两位数字开头,我们定义一个使用.substr仅返回前两位数的启动函数。此引导值将传递给闭包中的return函数,仅用于比较,同时保留要排序的原始值。

然后我们定义一个辅助“then by”排序函数,它采用与第一个相同的形式(你只传入by()的另一个实例)。在这个辅助by()函数中,我们定义了另一个启动函数,它再次使用.substr来返回字符串的后半部分。

输出完整的工作示例:

/* THE FUNCTION */
var by = function (path, reverse, primer, then) {
  
        // Light weight json deep access
    var get = function (obj, path) {
            if (path) {
                path = path.split('.');
                for (var i = 0, len = path.length - 1; i < len; i++) {
                    obj = obj[path[i]];
                };
                return obj[path[len]];
            }
            return obj;
        },
        
        // Invokes primer function if provided
        prime = function (obj) {
            return primer ? primer(get(obj, path)) : get(obj, path);
        };
    
    // Actual sorting function to be returned to native .sort method
    return function (a, b) {
        var A = prime(a),
            B = prime(b);
        
        return (
            (A < B) ? -1 :
            (A > B) ?  1 :
            // If A == B, then sort by supplemental 'by' function received as 'then' 
            (typeof then === 'function') ? then(a, b) : 0
        ) * [1,-1][+!!reverse];
    };
};

/* THE ARRAY */
var arr = ["10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long"];

/* THE EXAMPLE */
arr.sort(
    by(null, false,
        function (x) {
            var y = x.substr(0,2);
            return parseFloat(y);
        },
        by(null, false,
            function (x) {
                var y = x.substr(2);
                return y;
            }
        )
    )
);

// Output
var t1 = document.getElementById('t1');
t1.innerHTML += '<caption>Sort by, then by</caption>';
for (var i = 0; i < arr.length; i++) {
    t1.innerHTML += '<tr><td>' + arr[i] + '</td></tr>';
}
html { font: normal 62.5% Arial, sans-serif; }
body { padding: 10px; }
table {
    font-size: 1.3em;
    margin-bottom: 18px;
    width: 50%;
    border: none;
}
table caption {
    font-weight: bold;
    font-size: 1.5rem;
}
table td {
    color: #333;
    padding: 9px;
    vertical-align: middle;
    text-align: left;
    line-height: 1em;
    border-bottom: 1px solid #bcbec0;
    font: normal 1.3em monospace;
}
<table id="t1"></table>