1

Why my comparison in if doesn't work? The answer should be 8 but it returns 0.

   function findMissing(missingArray){
     var getArray = missingArray.sort();
     var myArray = [0,1,2,3,4,5,6,7,8,9]; 
       for(var i=0 ; i< myArray.length ; i++){
         for(var j=0 ; j< getArray.length ; j++){
            if(myArray[i] != getArray[j]){
                  return i;
          }
      }
   }
}
findMissing([0,3,4,5,7,2,9,1,6]);

1
  • 1
    Why do you think the answer should be 8? It clearly returns 0 when i===0 and j===1. Commented Jul 2, 2014 at 6:57

3 Answers 3

3

You can simply do it with 1 loop and array search to find the missing element. Looping over both arrays index gets changed every time and that comparison is not valid.

No Frills

 function findMissing(missingArray){
     var getArray = missingArray.sort();
     var myArray = [0,1,2,3,4,5,6,7,8,9]; 
       for(var i=0 ; i< myArray.length ; i++){
         if(getArray.indexOf(myArray[i])==-1)
            return i;
      }

  }
alert(findMissing([0,3,4,5,7,2,9,1,6]));     //8

Edit, Frills Version In fact you can create an array of all the missing elements, not just one. That be nice

 function findMissing(missingArray){
     var getArray = missingArray.sort();
     var myArray = [0,1,2,3,4,5,6,7,8,9]; 
     var returnArray=[];
       for(var i=0 ; i< myArray.length ; i++){
         if(getArray.indexOf(myArray[i])==-1)
             returnArray.push(myArray[i]);
      }
  return returnArray;
}

Fiddle

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

Comments

0
  function findMissing(missingArray){
     var getArray = missingArray.sort();

     var myArray = [0,1,2,3,4,5,6,7,8,9]; 

       for(var i=0 ; i< myArray.length ; i++){

            if(myArray[i] != getArray[i]){
                  return i;          
      }
   }
}
alert(findMissing([0,3,4,5,7,2,9,1,6]));

this should work now.

2 Comments

Nope Array size is not the same. Count those numbers
Although that comment is removed from the answer but still this wont answer the question. What if one array has length 10 and other has 5? you are using same index for both arrays which wont work if counts are not same.
0

When i=0 and j=1, myArray[0]=0 and getArray=3 which are not equal, so the condition in

myArray[i] != getArray[j]

evaluates to be true and function returns i i.e. 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.