Alex Rivera | Logout

Why or how does this prove JavaScript array equality?

Asked 2012-02-17T19:30:15.640
8

In this answer there is a simple function that will return array equality for arrays that contain primitive values.

However, I'm not sure why it works. Here is the function:

function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); }

I'm mostly interested in the second half; this bit:

!(a<b || b<a)

Why does the < and > work when comparing the arrays but the == doesn't?

How do the less than and greater than methods work within JavaScript?

Edit
Report

1 Answer

5

However, I'm not sure why it works.

It doesn't work. Consider

arrays_equal(["1,2"], [1,2])

produces true even though by any definition of array equality based on element-wise comparison, they are different.

arrays_equal([[]], [])

and

arrays_equal([""], [])

are also spurious positives.

Simply adding length checking won't help as demonstrated by

arrays_equal(["1,2",3], [1,"2,3"])

arrays_equal(
    ["",","],
    [",",""])

EDIT:

If you want a succinct way to test structural similarity, I suggest:

function structurallyEquivalent(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

It doesn't stop early on inputs that are obviously different -- it walks both object graphs regardless of how disimilar they are, but so does the function in the OP.

One caveat: when you're using non-native JSON.stringify, it may do strange things for cyclic inputs like:

var input = [];
input[0] = input;
answered 2012-02-17T19:40:53.430

Your Answer