Results 1 to 3 of 3

Thread: These two arrays look the same - JS says they aren't.

  1. #1
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default These two arrays look the same - JS says they aren't.

    I have two arrays that are populated a bit differently, but when they end up with the same content, my check reports that they are in fact different:



    The length property of both arrays is 16, and as you can see by the alert those 16 elements are indeed the same.

    Here is the code popping the alert:

    Code:
    if(array1 != array2){
    	alert("Javascript thinks the following are unequal:\n" + array1 + "\n" + array2);
    }
    What factors can cause two seemingly identical arrays like this to evaluate to unequal? Any help greatly appreciated!
    Last edited by jlizarraga; 11-03-2008 at 08:55 PM. Reason: resolved

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    An array is an object, not a string. Two objects are not equal unless they are the same object, just containing the same elements or properties is not enough. Since these aren't multidimensional arrays and all of the items are strings, you could test each item in one array against its counterpart in the other to see if they are equivalent, but they will never be equal in the strict javascript sense of the term as regards objects.

    Here's an easy but not foolproof method of checking the equivalency of items:

    Code:
    if(array1.join('$?!422') == array2.join('$?!422')) alert('arrays equivalent');
    This will work as long as none of the single elements in either array mimic two in the other in proper order and sequence with $?!422 strategically placed in that item. Also, this assumes two single dimensional arrays containing only strings or numbers.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. The Following User Says Thank You to jscheuer1 For This Useful Post:

    jlizarraga (11-03-2008)

  4. #3
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default

    Thanks a ton as usual, John!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •