Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap elements between arrays

I am trying to remove items from one array and add then to another. At some stage I will then add them back to the original array. When I run the array 10 times the 10th time does not return the expected result of full array = 0 remove array = 100; 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/

like image 211
nontechguy Avatar asked May 18 '26 00:05

nontechguy


1 Answers

please 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);
           }
      }   
 } 
like image 96
rajeshpanwar Avatar answered May 19 '26 15:05

rajeshpanwar