0

I have an array rosters and i want to alter this array according to some conditions. Here what I'm trying to do.

somefunction(callback) {
    for (var i in this.rosters) {
        var roster = this.rosters[i];
        if (roster.age > 7200) {
            this.rosters.splice(i, 1);
        } else {
            this.rosters[i].age = this.EMarshal.tu.getAgeOfTime(
                this.EMarshal.tu.getMyTime(
                    this.EMarshal.tu.getMyDate(roster.date), roster.shifttime
                )
            );
            console.log(this.rosters[i].age);
        }
    }
    callback();
}

When the the if condition is true and splice is been called, control comes out of from loop and call callback(). But i want to run the loop for each values in the array.

plz carefully notice that there are rosters and roster 2 different variables.

Any idea why its happening and the solution will be usefull. Thanks

PJ1405
  • 545
  • 1
  • 3
  • 18
  • 1
    `and splice is been called, control comes out of form loop ` - you lost me there – thefourtheye Mar 05 '15 at 05:53
  • it "from loop", now you ca ngo ahead. @thefourtheye – PJ1405 Mar 05 '15 at 06:01
  • The problem is that you're modifying the list while iterating through it. – Vitruvie Mar 05 '15 at 06:01
  • No i tried to store the indexes and run the splice for those index after the loop, same result i got. @Saposhiente – PJ1405 Mar 05 '15 at 06:04
  • It's generally a bad idea to modify a list while you're looping over it. It would be better to accumulate a list of things to remove, then remove them after the loop finishes. – Andrew Magee Mar 05 '15 at 06:04
  • 1
    Strongly recommend read: [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/q/500504/1048572) – Bergi Mar 05 '15 at 06:05
  • 1
    when you splice an index less than _i_, _i_ +1 becomes just _i_, then you increment, and thus skip over the old _i_ +1... – dandavis Mar 05 '15 at 06:16

1 Answers1

1

It's just because you are trying to alter the array on which you are iterating. So, just ad some logic to store the indexes as you have said you have tried. Here is one suggestion before getting into loop var index = []; then your if condition

if (roster.age > 7200) {
  index.push(i);
}

and then after the loop, remove those indexes from rosters

for (var j = index.length - 1; j > -1; j-- ) {
  console.log(j);
  this.rosters.splice(index[j], 1);
}

Remember to iterate the index from last index otherwise you will remove the 1st index and the trying to remove the last index from the rosters, but now you have removed the element from the array so the length is been changed.