简体   繁体   English

如何在javascript中对整数组合数组进行排序

[英]how to sort an integer combined array in javascript

I have an array like this in JS: 我在JS中有这样的数组:

var a = ["1", "2", "1_10", "1_22", "2_12", "3", "14", "1_15", "3_31", "14_25", "2_18"];

and I need to sort it, in order to look like this: 我需要对它进行排序,以便看起来像这样:

["1", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31", "14", "14_25"];

I tried using a function like the one in this fiddle http://jsfiddle.net/r7vQP/ but I am getting a wrong answer (["1", "14", "14_25", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31"]). 我尝试使用像这个小提琴http://jsfiddle.net/r7vQP/中的那个函数,但我得到一个错误的答案([“1”,“14”,“14_25”,“1_10”,“1_15”, “1_22”,“2”,“2_12”,“2_18”,“3”,“3_31”])。

Try this: 尝试这个:

var b = a;
for (var i = 0; i < b.length; i++) {
    b[i] = b[i].replace('_', '.');
}


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


for (var y = 0; y < b.length; y++) {
    a[y] = b[y].replace('.', '_');
}
function numericSort(a, b) {
    return a - b;
}

a.map(function (e) {
    return parseFloat(e.replace("_", "."));
})
.sort(numericSort)
.map(function (e) {
    return e.toString().replace(".", "_");
})
var a = ["1", "2", "1_10", "1_22", "2_12", "3", "14", "1_15", "3_31", "14_25", "2_18"];
function sortByFloat (a,b)
{
a=parseFloat (a.replace ("_",".")); b=parseFloat (b.replace ("_",".")); if (a<b) return -1; if (a>b) return 1; if (a==b) return 0; } a.sort (sortByFloat);

return ab would be faster instead of the three if conditions 如果条件,返回ab将更快而不是三

function to_dot(s) { return s.replace('_','.') }
function from_dot(n) { return n.replace('.','_') }

a.map(to_dot).sort(function(a,b){return a-b}).map(from_dot)

["1", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31", "14", "14_25"] [“1”,“1_10”,“1_15”,“1_22”,“2”,“2_12”,“2_18”,“3”,“3_31”,“14”,“14_25”]

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

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