0

I have an array with functions/Objects in it. This Objects have a function to test itself and if they fail they get removed from the array. If I run a forEach on this array and run this testfunction and one object gets removed from the array the forEach loop skips an object.

What is a good way to solve this problem?

Here a example. Run the example and you will see the the 2ed Object tests.push(new Test(2)); is skipped in the forEach loop.

//creating a test array
var tests = [];
tests.push(new Test(1));
tests.push(new Test(2));
tests.push(new Test(3));
tests.push(new Test(4));

function Test(n) {
  this.n = n;

  this.testme = function() {
    if(this.n < 3) {
	  tests.splice(tests.indexOf(this), 1); //remove me from the array tests please!
	  console.log(this.n, "I got removed!");
    } else {
      console.log(this.n, "I can stay!");
    }
  } 
}


console.log("tests length: ", tests.length);

tests.forEach(function(t) {
  t.testme();
});

console.log("tests length: ", tests.length); //output should now be 2 

3

2 Answers 2

3

why not use the built in filter function?

tests = tests.filter(t => t.testMe());
Sign up to request clarification or add additional context in comments.

4 Comments

This will require modifying the existing testme function
For my real project I am not able to use the return value, but I would be able to set a flag (see my answer to jmargolisvts commet). I wonder, which one is more efficient. using the filter method on the array after I am done with the forEach loop, or use splice, but use the trick from GetOfMyLawns answer (loop backwards over the array) and then use splice in the array.
yea but it'd be simpler, just return this.n >= 3)
Yeah, my comment is just a note, without modification, the end result is 0 in my test.
2

What you will want to do is loop over the array in reverse:

let i = tests.length
while(i--) tests[i].testme()

Here it is in action:

//creating a test array
var tests = [];
tests.push(new Test(1));
tests.push(new Test(2));
tests.push(new Test(3));
tests.push(new Test(4));

function Test(n) {
  this.n = n;

  this.testme = function() {
    if(this.n < 3) {
	  tests.splice(tests.indexOf(this), 1); //remove me from the array tests please!
	  console.log(this.n, "I got removed!");
    } else {
      console.log(this.n, "I can stay!");
    }
  } 
}


console.log("tests length: ", tests.length);

let i = tests.length
while(i--) tests[i].testme()

console.log("tests length: ", tests.length); //output should now be 2

2 Comments

cool work around! This will also work if I later add again new objects to the array, right?
Yeah it will work when you add/remove/modify the array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.