title: JavaScript - add / remove elements of array of objects during iteration
body: <p>I have a case where I need to iterate through an array of objects, check a conditional on each element , delete existing object &amp; add new object based on the outcome of the conditional. The code I have currently is as below, but of course it doesn't work. </p>
  
  <p>What is the right approach to iterate through an array while adding / deleting new elements on certain iterations.</p>
  
  <pre><code>var arrayOfObjects = [] // a list to store objects of the same time
  for(var i = 0; i &lt; 5; i++){
    arrayOfObjects.push(new someClass());
  }
  
  while(true){
    for(var obj in arrayOfObjects){
      // some conditional check on obj
      // if check is true, delete the obj from array &amp; add a new object
      arrayOfObjects.splice(arrayOfObjects.indexOf(obj),1);
      arrayOfObjects.push(new someClass());    
    }
  }
  </code></pre>