Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript surprising array comparison

I'm trying to compare two arrays in javascript.

What I'd like is:

a < b &iff; ∃ i ≥ 0 s.t. a[i] < b[i] and ∀ 0 ≤ j < i, a[j] = b[j]

So arrays of non-negative numbers work as desired:

firebug> [0,1,2,3,4] < [1,0,0] true 

And comparing negative numbers with zero works as expected:

firebug> [-1, 1] < [0, 0] true 

But comparing negative numbers with negative numbers is... suprising:

firebug> [-2] < [-1] false firebug> -2 < -1 true 

What's going on here, so I can correct my intuition for what array comparison means in javascript?

like image 789
rampion Avatar asked Nov 30 '11 15:11

rampion


1 Answers

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.

like image 187
pimvdb Avatar answered Sep 22 '22 10:09

pimvdb