Search code examples
javascriptarrayssortcomparefunction

Javascript Array sort compare function weird ordering


So I am wondering what is wrong with my code that gets the sort with compare argument return the correct order for all numbers but 5. I have a feeling it has something to do with how I unshifted the numbers 12, 4, 94, and 1 but I am a complete newbie and am quite confused. Thanks in advance!

<!DOCTYPE html>
<html>
<head>
    <title>Array Manipulation:Sort</title>
    <script type="text/javascript">

        var parts = [];

        parts.push("5", "42", "12");

        var removed = parts.pop();

        alert(removed);


        function compare(value1, value2) {
            if (value1 < value2) {
                return -1;
            } else if (value1 > value2) {
                return 1;
            } else {
                return 0;
            }
        }

        parts.unshift(12, 4, 94, 1);

        alert(parts.sort());            //1, 12, 4, 42, 5, 94
        alert(parts.sort(compare));     //1, 4, 12, 42, 5, 94


    </script>
</head>
</html>

Solution

  • I suggest to treat all values as number and return the delta, with an implicit type casting to number.

    function compare(value1, value2) {
        return value1 - value2;
    }
    

    function compare(value1, value2) {
        return value1 - value2;
    }
    
    var data = [12, 4, 94, 1, "5", "42"];
    
    data.sort(compare);
    
    console.log(data);
    .as-console-wrapper { max-height: 100% !important; top: 0; }