0

Goodmorning,

I would like to remove an object from an array after it is used in a forEach loop. And then the foreach loop should continue with the next object left in the array.

However right now it runs the function for the first object, then I remove this first object and then the function stops running.

This is my script:

function test() {
  // Create array with id's of mailings to get from database
  var allAutomations = [
    {"id": "52"},
    {"id": "72"}
  ] 

  allAutomations.forEach(function(automation, index) {

    var a = 1;
    while (a <= 10) {
      console.log(a);
      a++
    }

    allAutomations.splice(index, 1);

    console.log(allAutomations);
          
  });
}

test();

As you can see in console at removing the current object works, but after that it should run the while loop for the one with id '72' again.

Anybody knows how to fix this?

  • 1
    forEach iterates on the first item, then move on to the second item, but the second item does not exists because the array length is 1 after you have removed the first item, so the loop ends. Removing array item during iteration is usually not a good idea. If you do not really need to do so, don't do it. – Ricky Mo Apr 22 '22 at 08:26
  • 1
    Why do you remove the element _in_ the `.forEach()`? Just iterate over the elements and reset the elements _after_ the `.forEach()` – Andreas Apr 22 '22 at 08:27
  • @RickyMo _"so the loop ends"_ - The "loop" doesn't stop (steps 2+5), only the callback is skipped (steps 5b+5c) -> https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.foreach – Andreas Apr 22 '22 at 08:30
  • I have to remove the element because this is just a small part of my script. It's a script with some API calls in a while loop with a foreach loop. After finishing the foreach part for the first object, I want to remove it. In case the API throws an error it won't start at the first object again, but with the second. – SybrenMeister Apr 22 '22 at 08:36
  • I found this solution works perfectly: https://stackoverflow.com/a/40706051/18371936 Using filter instead of splice. It was in the post Pete mentioned. Thanks @Pete! – SybrenMeister Apr 22 '22 at 08:37
  • There's nothing in your question that could be used for filtering. If [that](https://stackoverflow.com/a/40706051/18371936) really works for you then your question is not a [mcve] ;) – Andreas Apr 22 '22 at 08:38

0 Answers0