javascript surprising array comparison javascript surprising array comparison arrays arrays

javascript surprising array comparison


The array is converted to a string, which comes down to .join(), which in turn joins the elements with a comma (,) as delimiter.

"-1,1" < "0,0" === true

because the character code of - (45) is smaller than the character code of 0 (48).

On the other hand,

"-2" < "-1" === false

because the second character codes are compared (the first are both -, so that doesn't give a result yet), and the character code for 2 (50) is bigger than the character code of 1 (49), so this yields false.

It comes down to a lexographical sorting (i.e. by character codes) and not a numerical one, even if the elements are numbers (because of the string coercion).

Basically comparing arrays is not recommended. It is implicitly defined as string comparison, but this can yield surprising results.


There's no such thing as JavaScript array comparison in any form similar to what you describe.

What's happening in all cases is that your arrays are being converted first to strings by joining their contents together. Thus, the string "-2" is not less than the string "-1", because the character "2" comes after "1" in the character set. Similarly, "-1,1" is less than "0,0" because the "-" character comes before the digits.

You can see for yourself that in all cases your comparisons:

array1 < array2

get exactly the same results as:

("" + array1) < ("" + array2)

or:

array1.join(",") < array2.join(",")


I couldn't find an answer about how to actually compare arrays in Javascript and get "expected" results, so here is the code

compareArrays = function(a, b) {  var elA, elB, i, len;   for (i = 0, len = Math.min(a.length, b.length); i < len; i++) {                   elA = a[i], elB = b[i];    if (elA > elB) return 1;    if (elA < elB) return -1;  }  return b.length - a.length;};console.log(compareArrays([-2], [-1])) # -1console.log(compareArrays([], [])) # 0console.log(compareArrays([null], [undefined])) # 0console.log(compareArrays([1, 2, 3], [1, 2, 3, 4])) # 1console.log(compareArrays([0, 2], [0, 1])) # 1console.log(compareArrays([1], [NaN])) # 0console.log(compareArrays([NaN], [1])) # 0