Results 1 to 2 of 2

Thread: Compare 2 Arrays

  1. #1
    Join Date
    Mar 2010
    Location
    Canada
    Posts
    32
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Compare 2 Arrays

    I have 2 arrays and I would like to compare the 2 arrays.
    If an element in array 1 is NOT in array 2 then I would like to display that element.

    In this case, I should only display the letter "c" but it doesn't work and I don't know why??
    Here's my code:


    HTML Code:
    <html><head>
    <script type="text/javascript">
    function getValue(id){
       var x=new Array("a","b","c","d","e");
       var y=new Array("a","b","3","d","e");
       var str="";
    
       for (var i=0; i<x.length; i++){
          for (var j=0; j<y.length; j++){
             if (x[i] == y[j]){
           	    break;
    	 }else{
                //Check if reach the last element in the array 2
                //If yes, then display that element in array 1 b/c not in array 2
                if (y[j] == y.length-1){
    	       str += x[i];
                }
             }
          }
       }
       document.getElementById(id).innerHTML = str;
    
    }
    
    
    function init(){
       getValue("info");
    }
    </script>
    </head>
    
    <body onload="init()">
    <h2 id="info"></h2>
    </body>
    </html>

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,167
    Thanks
    44
    Thanked 3,240 Times in 3,201 Posts
    Blog Entries
    12

    Default

    Code:
    if (y[j] == y.length-1){
    should be:

    Code:
    if (j == y.length-1){
    - John
    ________________________

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

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
  •