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.

Leave a Comment