0

I have two identical array and I want to see if it equals and return true

var a = [1,2];

var b = [1,2];

if (a===b) { return true }

these two array are obviously identical but I am getting not equal. Can some explain why and if there is an easy way to compare the two?

Son Truong
  • 233
  • 1
  • 3
  • 7
  • There arrays are not identical, although they are structurally equivalent. –  Jun 09 '15 at 07:20
  • You are comparing the reference to the array, which in your case, is different, as they are two different arrays, that happen to have similar data. See http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript on how to compare their values instead. – ericosg Jun 09 '15 at 07:20

4 Answers4

1

Problem is you are creating two different arrays, and === check whether both a and b have same reference. Hence your condition fails. There is no built-in code to compare array, however there are libraries for the same. But you simply write a function to compare the arrays by looping.

1

1. Don't ever use == operator

It doesn't do what you think and it's quite close to be totally useless (for example "1" == [[1]]). Prefer === instead. If the type is the same for both sides == and === do the same, but if they're not == does crazy conversions you will regret.

2. === for arrays checks identity

I.e. it will return true only if the two sides are the very same object, not an object with the same content (whatever 'same' is meant to be).

If you want to check the content you should first decide how to compare elements... for example

my_eqtest([1, [2, 3]], [1, [2, 3]])

should return true or false?

x = [1, 2]
y = [1, 2]
y.myextramember = "foo"

my_eqtest(x, y) // should be true or false?

You should describe (document) what you mean for equality if it's not object identity, otherwise who reads the code will not understand why something is not working (including yourself in a few weeks).

6502
  • 112,025
  • 15
  • 165
  • 265
0

Easiest way would be use a utility library like lodash _.difference

Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44
0

try this:

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }
    return true;
}
Abraham Uribe
  • 3,118
  • 7
  • 26
  • 34
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59