Javascript sort()混合数据类型数组



如果我有一个这样的数组:

["23", "765", "sfasf", "2.3E-3", "2.3cE-3"]

我如何排序它,使数字(小数,浮点数或科学记数法)升序和之后的字符串不是数字(例如"sfasf"或"2.3cE-3")?

示例数组的期望顺序:

["2.3E-3", "23", "765", "2.3cE-3", "sfasf"]

不能转换为数字的字符串的顺序无关紧要,它们必须在末尾。

答案:

 $scope.cleanAndOrder = function(dbo, fieldName) {
    var textareaId = "textarea"+"_"+fieldName ;
    var textarea= document.getElementById(textareaId);
    //(+b && (+a!=a)) : return true (converted to 1) if b is a number and a isn't
    //(a-b) : then compare the numbers if the first comparaison isn't enough
    textarea.value = dbo.attributes[fieldName].sort(function(a,b){ return (+b && !+a) || (a-b) }).join("n");
    var lines = textarea.value.split("n");
    textarea.setAttribute('rows', lines.length +2);
 }

你可以做

var arr = arr.sort(function(a,b){ return ((+b==b) && (+a!=a)) || (a-b) })

这个想法是做两个比较:

  • (+b==b) && (+a!=a):如果b是数字且a不是
  • ,则返回true(转换为1)
  • a-b:如果第一次比较不够,然后比较数字

更深入:+aa转换为数字。当且仅当+a是数字(请记住,NaN不等于NaN)时,它等于(对于==,而不是for ===) a

sort函数接受函数比较作为参数

定义你

function compareFct(a, b) {
    if (isNaN(a)) {
        if (isNaN(b)) {  // a and b are strings
            return a.localeCompare(b);
        } else {         // a string and b number
            return 1;  // a > b
        }
    } else {
        if (isNaN(b)) {  // a number and b string
            return -1;  // a < b
        } else {         // a and b are numbers
            return parseFloat(a) - parseFloat(b);
        }
    }
}

,像

一样使用
yourArray.sort(compareFct);

最新更新