Compare 2 Arrays RRS feed

  • Question

  • 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:


    <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]){
                //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(){
    <body onload="init()">
    <h2 id="info"></h2>


    Friday, December 16, 2011 1:28 AM


  • Hello H,

    You have the tools to debug this problem yourself so I want to help you discover the issue and give you some tools to help yourself.

    It literally took me less than a minute to troubleshoot the issue and you too can do this!

    The key to problems like this is to walk through them in the debugger and then look at the variables as you do this.  Since this did not depend on Metro App classes you can use The Internet Explorer debugger (you could put this in your metro app and debug too) to see this.

    1. Create a file called test.htm and put your code in it.
    2. Open the file by double clicking on it and choose 'allow blocked content' from the toast at the bottom of IE when you start.
    3. Hit the F12 key to bring up the developer tools
    4. Click on the 'Script' tab.  You should see your script.
    5. Click on the first line in your function where you create the 'x' arrary.
    6. Hit the F9 key to place a breakpoint
    7. Hit the 'Start debugging' button and this will reload your page and the debugger will stop on your breakpoint
    8. Click the 'Locals' view on the right to inspect the values of the local variables as you step through your code.
    9. Hit F10 to step through your code
    10. If you want to see a particular variable use the mouse... Click and highlight something (like x[i]) and then hover the mouse over it to see the value.

    You should find your error very quickly!






    Jeff Sanders (MSFT)
    Friday, December 16, 2011 2:25 PM