Swapping items between arrays

I am trying to remove elements from one array and then add them to another. At some point, I'll add them back to the original array. When I run the array 10 times for the 10th time, it does not return the expected full array = 0 remove array = 100; Does anyone know why this would be the case?

 var fullArr = [];//contains all items
 var remArr = [];//contains removed items
 var userAnswer = true;//this would be user input

 populateArray();
 runTenTimes();
 //getting the answer right 10 times should result in fullArr.length = 0; remArr.length = 100;

 function runTenTimes(){
     for(var i=0;i<10;i++){
     //console.log(i);
     checkUserAnswer();   
     }
 }
 function populateArray(){
     for(var i=0;i<100;i++){
         fullArr.push(i);
     }
 }

function checkUserAnswer(){
     if(userAnswer){//only if true
         for(i=0;i<10;i++){//10 because I remove 10 at a time
           removeShape(fullArr,fullArr[i],remArr);
         }
     }else{
          // add elements from remove arr
          // back into full array   
     }
     console.log("full array : " + fullArr.length);
     console.log("remove array : " + remArr.length);
     console.log("------------------")
 }

 function removeShape(arr,item,rem){
      for(var i = 0;i<arr.length; i++) {
           if(arr[i] === item) {
             rem.push(arr[i]);
             arr.splice(i, 1);
           }
      }   
 } 

      

http://jsfiddle.net/non_tech_guy/vy671jv4/

+3


source to share


2 answers


use this code



var fullArr = [];//contains all items
 var remArr = [];//contains removed items
 var userAnswer = true;//this would be user input

 populateArray();
 runTenTimes();
 //getting the answer right 10 times should result in fullArr.length = 0; remArr.length = 100;

 function runTenTimes(){
     for(var i=0;i<10;i++){
     //console.log(i);
     checkUserAnswer();   
     }
 }
 function populateArray(){
     for(var i=0;i<100;i++){
         fullArr.push(i);
     }
 }

function checkUserAnswer(){
     if(userAnswer){//only if true
         var arrCopy = fullArr.slice(0);
         for(i=0;i<10;i++){//10 because I remove 10 at a time
           removeShape(fullArr,arrCopy[i],remArr);
         }
     }else{
          // add elements from remove arr
          // back into full array   
     }
     console.log("full array : " + fullArr.length);
     console.log("remove array : " + remArr.length);
     console.log("------------------")
 }

 function removeShape(arr,item,rem){
      for(var i = 0;i<arr.length; i++) {
           if(arr[i] === item) {
             rem.push(arr[i]);
             arr.splice(i, 1);
           }
      }   
 } 

      

+3


source


changing to forEach still produced an error until I changed arr.shift () and not arr.splice (i, 0).



function removeShape(arr,item,rem){
      arr.forEach(function(){
        if(arr[i] === item) {
             rem.push(arr.shift());
          }
       })
}

      

0


source







All Articles