Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Javascript array compared? [duplicate]

Is there a standard defined how would JavaScript be compared, on Chrome console I get this

[10,0,0] > [1,0,0]
true
[10,0,0] > [5,0,0]
false
[5, 0, 0, 0] < [10, 0, 0, 0] //repeatable
false

[10,0,0,0] > [9,0,0,0]
false
[11,0,0,0] > [10,0,0,0]
true

Which is highly unintutive, and I can't even make sense what logic is being applied, and they look repeatable so doesn't look based on object id(ref) etc, so is there any documentation for it?

like image 791
Anurag Uniyal Avatar asked Jun 06 '13 06:06

Anurag Uniyal


2 Answers

JavaScript arrays are converted to strings and the strings are then compared. So.

[10,0,0].toString() => "10,0,0"
[5,0,0].toString() => "5,0,0"

Strings are compared lexicographically, so "5,0,0" is bigger than "10,0,0".

like image 165
Stasik Avatar answered Oct 10 '22 08:10

Stasik


Something like this may help you,

JSON.stringify([2,2,2]) === JSON.stringify([2,2,2]); //true

Cheers :).

like image 45
Indrajit Das Avatar answered Oct 10 '22 09:10

Indrajit Das