1

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
    My guess is because you are mixing strings and numbers. – Josh Feb 04 '17 at 19:11
  • 1
    Some of your array items are numbers, some of them are strings. That doesn't work out. Do you want to compare them by numeric value or by lexical characters? – Bergi Feb 04 '17 at 19:11
  • See also [How to sort an array of integers correctly](http://stackoverflow.com/q/1063007/1048572) - not sure what your question is, maybe it's a duplicate? – Bergi Feb 04 '17 at 19:13

3 Answers3

0

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

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;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    You might want to mention that using `-` implicitly casts them – Bergi Feb 04 '17 at 19:15
  • Thanks for the explanation Bergi; do any operators implicitly cast variables as number type? – Tejas Harith Feb 04 '17 at 20:00
  • basically all [Arithmetic Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators) convert to number, but not plus, because if any operand is a string, the result is a string, too. – Nina Scholz Feb 04 '17 at 20:05