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?

1
  • 1
    stackoverflow.com/questions/6229197/… last ans: When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents. Commented Oct 16, 2012 at 9:07

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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!

5 Comments

[1,2,3] and [1,1,2,3], are they Identical?
@xdazz Thank bruv :) fixed jsfiddle.net/ASnYu/1 and working jsfiddle.net/ASnYu
[1,2,3] and [2,1,3], are they identical?
@DavidHedlund +d, thanks for the comment bruver :)) I reckon order is different but both contain the same element, I will see how I can squeeze in the order check as well :),
@DavidHedlund Enhanced Fixed for the order as well :) jsfiddle.net/Putjc Thanks man!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.