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

前端 未结 4 950
南方客
南方客 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条回答
  •  鱼传尺愫
    2021-01-05 00:56

    You should first check to see if either value is null and return the opposite value.


    On a side note:

    For your default _order value, you should check if the parameter is undefined instead of comparing its value to null. If you try to compare something that is undefined directly you will get a reference error:

    (undefinedVar == null) // ReferenceError: undefinedVar is not defined
    

    Instead, you should check if the variable is undefined:

    (typeof undefinedVar == "undefined") // true
    

    Also, it's probably a better idea to wrap your compare function in a closure instead of relying on a global order variable.

    Sometime like:

    [].sort(function(a, b){ return sort(a, b, order)})
    

    This way you can sort at a per-instance level.


    http://jsfiddle.net/gxFGN/10/

    JavaScript

    function sort(a, b, asc) {
        var result;
    
        /* Default ascending order */
        if (typeof asc == "undefined") asc = true;
    
        if (a === null) return 1;
        if (b === null) return -1;
        if (a === null && b === null) return 0;
    
        result = a - b;
    
        if (isNaN(result)) {
            return (asc) ? a.toString().localeCompare(b) : b.toString().localeCompare(a);
        }
        else {
            return (asc) ? result : -result;
        }
    }
    

提交回复
热议问题