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

前端 未结 4 970
南方客
南方客 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:39

    function sortByDataString(a, b) {
        if (a === null) {
            return 1;
        }
        if (b === null) {
            return -1;
        }
        if (isNumber(a) && isNumber(b)) {
            if (parseInt(a,10) === parseInt(b,10)) {
                return 0;
            }
            return parseInt(a,10) > parseInt(b,10) ? 1 : -1;
        }
        if (isNumber(a)) {
            return -1;
        }
        if (isNumber(b)) {
            return 1;
        }
        if (a === b) {
            return 0;
        }
        return a > b ? 1 : -1;
    }
    

    fiddle here: http://jsfiddle.net/gxFGN/6/

    I left out the order parameter, but you could always reverse the array at the end if needed.

提交回复
热议问题