How can one compare string and numeric values (respecting negative values, with null always last)?

前端 未结 4 977
南方客
南方客 2021-01-05 00:03

I\'m trying to sort an array of values that can be a mixture of numeric or string values (e.g. [10,\"20\",null,\"1\",\"bar\",\"-2\",-3,null,5,\"foo\"]). How can

4条回答
  •  猫巷女王i
    2021-01-05 00:37

    Use this:

    function typeOrder(x) {
        if (x == null)
            return 2;
        if (isNaN(+x))
            return 1;
        return 0;
    }
    function sortNumber(a, b) {
        a = parseInt(a, 10); b = parseInt(b, 10);
        if (isNaN(a) || isNaN(b))
            return 0;
        return a - b;
    }
    function sortString(a, b) {
        if (typeof a != "string" || typeof b != "string")
           return 0;
        return +(a > b) || -(b > a);
    }
    
    order = order == "dsc" ? -1 : 1;
    numericArr.sort(function(a, b) {
        return order * ( typeOrder(a)-typeOrder(b)
                         || sortNumber(a, b)
                         || sortString(a, b)
                       );
    });
    

    (updated fiddle)

提交回复
热议问题