Javascript Array sort compare function weird ordering

636 Views Asked by At

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>
3

There are 3 best solutions below

3
On BEST ANSWER

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; }

0
On

Change this

var parts = [];
parts.push("5", "42", "12");

to

var parts = [];
parts.push(5, 42, 12);

So That you can compare just numbers and for comparison :

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

When you compare a string to a number, it converts both to numbers, looks for the first character which is different and then acts based on that.

"5" > "42"

Explicitly convert your strings to numbers to fix this.

    function compare(value1, value2) {
        value1 = +value1;
        value2 = +value2;