0

I've got two lists. When I run array1 == array2, the console prints false. If I iterate through them and check equality for each item, it prints true every time. What's wrong?

for (var i=0; i<array1.length; i++) {
    console.log(array1[i] == array2[i]);
}

From the Safari console:

enter image description here

All my google searches turned up things about array diffs and checking equality of unordered arrays. I thought there must be an easier way to solve the problem of two lists in the same order, and I couldn't find that online.

Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
  • It is like this: array1 = 0x234khwsio3 and array2 = 0x2h29ouhwe. (Not real hex values there - just random garbage.) So array1 != array2 because they are not at the same location in memory. BUT! The contents are the same because the lists are the same. – Mark Manning Mar 29 '16 at 01:54
  • @HankyPanky Yeah, it is. Sorry. All my google searches turned up things about array diffs and checking equality of unordered arrays. Why this didn't work was confusing and frustrating to me with my Python background (in which everything always works magically) – Luke Taylor Mar 29 '16 at 01:59
  • As @MarkManning pointed out, you are pointing to two different places in memory, and hence they are not equal. However when you deep compare the arrays, you are comparing the literal constants (string 'abc' will always have the same value in memory etc) which are in the same place in memory, and hence you see equality. – char Mar 29 '16 at 01:59
  • 4
    i've got two pairs of shoes, but my feet are the same no matter which i wear... – dandavis Mar 29 '16 at 02:02
  • Dan you made my day thanks.+1 – Train Mar 29 '16 at 02:15
  • @dandavis Very witty +1 :-) – Mark Manning Mar 29 '16 at 02:15
  • 1
    just to stretch the analogy to the limit: i can also refer to the same pair of shoes with many names: newer, nice, brown, leather, etc, and those names will still apply if someone else wears the shoes... – dandavis Mar 29 '16 at 02:25
  • I get that this is a duplicate, but why the downvote? It's still a minimal, complete, and verifiable example, and it shows some research effort. It's a good question, albeit one that has been asked before. – Luke Taylor Mar 29 '16 at 11:25

1 Answers1

1

use array1[i].equals(array2[i]) Like it was stated in the comments you are not comparing the contents with the ==.

Train
  • 3,420
  • 2
  • 29
  • 59