SitePoint Sponsor

User Tag List

Results 1 to 6 of 6

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2010
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,718
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Using a filter, you can loop through both arrays, where the items from the first array are el, and the second array are accessed from the this keyword.

    Code javascript:
    function nonMatching(el, i) {
        return (el != this[i]);
    }
    var x = ['a', 'b', 'c', 'd', 'e'],
        y = ['a', 'b', '3', 'd', 'e'],
        str = x.filter(nonMatching, y).join(', ');

    str will be 'c'
    If there are other non matching ones, such as e, str will be 'c, e'

    The filter page has compatibility code to supply the array filter functionality to less capable web browsers (such as IE)
    Last edited by paul_wilkins; Dec 16, 2011 at 03:26.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,718
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    The above checks that each item in the first array matches at the same location in the second array.

    If you want to check if each item in the first array exists anywhere in the second array, you can use The array indexOf method to check for that instead. Compatibility code for less capable browsers (Internet Explorer) is at that link too.

    Code javascript:
    function nonExisting(el) {
        return (this.indexOf(el) === -1);
    }
    var x = ['a', 'b', 'c', 'd', 'e'],
        y = ['a', 'b', '3', 'd', 'e'],
        str = x.filter(nonExisting, y).join(', ');
    alert(str);

    str will be 'c'
    If there are other non matching ones, such as e, str will be 'c, e'
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Addict
    Join Date
    Aug 2006
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
      
    <html><head>
    
    <script type="text/javascript">
    // http://www.w3schools.com/jsref/jsref_slice_array.asp
    // http://www.w3schools.com/jsref/jsref_splice.asp
    
    function getValue(id){
       var x=new Array("a","b","c","d","e");
       var y=new Array("a","b","3","d","e");
       var A = x;
    
       //alert(A);
    
       for (var i=0; i<x.length; i++){
          for (var j=0; j<y.length; j++){
             if (x[i] === y[j]) {  A.splice(i,1);  }
       }
       
    var el= document.getElementById(id);
    el.innerHTML = A;
    
    }
    }
    
    function init(){
       getValue("info");
    }
    </script>
    </head>
    
    <body onload="init()">
    <h2 id="info"></h2>
    </body>
    </html>
    I wrote
    var A = x.slice(0);
    instead of
    var A = x;

    if I write var A = x;
    The output of the code above will be: c

    if I write var A = x.slice(0);
    The output of the code above will be: b,d,e

    The output of the codes are not the same. Why?
    Bismillahirrahmanirrahîm
    Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,718
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by muazzez View Post
    I wrote
    var A = x.slice(0);
    instead of
    var A = x;

    results are not the same. Why?
    With the first one, A becomes a copy of the x array, so x doesn't become affected when you change A in the loop.
    With the second, A is a reference to the x array, so when you remove items from A they are also removed from x, because both A and x are references to the same array.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Addict
    Join Date
    Aug 2006
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    With the first one, A becomes a copy of the x array, so x doesn't become affected when you change A in the loop.
    With the second, A is a reference to the x array, so when you remove items from A they are also removed from x, because both A and x are references to the same array.
    Thanks...

    I wrote this
    if (A[i] === y[j])
    instead of
    if (x[i] === y[j])


    and I change this
    for (var i=0; i< x.length; i++)
    to
    for (var i=0; i< A.length; i++)

    The code is working as I expected.
    Code:
    <html><head>
    
    <script type="text/javascript">
    // http://www.w3schools.com/jsref/jsref_slice_array.asp
    // http://www.w3schools.com/jsref/jsref_splice.asp
    
    function getValue(id){
       var x=new Array("a","b","c","d","e");
       var y=new Array("a","b","3","d","e");
     //var A = x;
    var A = x.slice(0);
       //alert(A);
    
       for (var i=0; i< A.length; i++){
          for (var j=0; j<y.length; j++){
             if (A[i] === y[j]) {  A.splice(i,1);  }
          }
       }   
    var el= document.getElementById(id);
    el.innerHTML = A;
    
    alert("x = "+x);
    }
    
    function init(){
       getValue("info");
    }
    </script>
    </head>
    
    <body onload="init()">
    <h2 id="info"></h2>
    </body>
    </html>
    Bismillahirrahmanirrahîm
    Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.


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
  •