5

I have two jQuery arrays initialList and newList.

I first compare them like so:

initialList == newList

This returns false.

Then I compare element by element:

$.each(initialList, function(idx, element){ console.log(element == newList[idx] )});

Every comparison is true.

So if all elements are identical why return false in the first comparison?

Virgiliu
  • 3,068
  • 6
  • 32
  • 55
  • 1
    http://stackoverflow.com/questions/6229197/how-to-know-if-two-arrays-have-the-same-values last ans: When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents. – Mifeng Oct 16 '12 at 09:07

2 Answers2

5

You're asking if they're equivilent (all items the same), whereas the == operator is checking if they are the same thing (references to the same object). They're not, so == returns false.

If you're asking philosophically why == doesn't evaluate the operands and tell you if for all intents and purposes they're 'the same', you can read more about equivalence verses equality on Wikipedia (Object identity vs. Content equality).

Steve Wilkes
  • 7,085
  • 3
  • 29
  • 32
2

See this demo: http://jsfiddle.net/pEzAW/

Now when you use == operator you are trying to compare one object with another object not its state, where as in the loop version you are comparing the elements.

You can do a way simpler version like this: to check the length as well see this: http://jsfiddle.net/ASnYu/1/

arr1 = [1,2,3]
arr2 = [1,2,3]

alert(arr1 == arr2)


if ($(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0 && arr1.length == arr2.length)
    alert("Two arrays are Identical");​

If order is important for identity do this using https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/ValueOf

http://jsfiddle.net/Putjc/

code

arr1 = [1, 2, 3]
arr2 = [2, 1, 3]

if ($(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0 && arr1.length == arr2.length && arr1.valueOf().toString() == arr2.valueOf().toString()) 
         alert("Two arrays are Identical"); 
else alert("two arrays are **not** identical");​

Random interesting read: Is jQuery an Array?

Rest hope it fits the cause!

Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77