Splicing a Javascript array from within the callback passed to forEach
arrays, foreach, javascript
Solution
Lets see why JavaScript behaves like this. According to the ECMAScript standard specification for `Array.prototype.forEach`,
when you delete an element at index 1, the element at index 2 becomes the element at index 1 and index 2 doesn't exist for that object.
Now, JavaScript looks for element 2 in the object, which is not found, so it skips the function call.
That is why you see only `a` and `b`.
The actual way to do this, is to use `Array.prototype.filter`
var array = ["a", "b", "c"];
array = array.filter(function(currentChar) {
console.log(currentChar); // a, b, c on separate lines
return currentChar !== "b";
});
console.log(array); // [ 'a', 'c' ]
Problem
I have this code which is supposed to iterate over each item in an array, removing items based on some condition: ``` //iterate over all items in an array //if the item is "b", remove it. var array = ["a", "b", "c"]; array.forEach(function(item) { if(item === "b") { array.splice(array.indexOf(item), 1); } console.log(item); }); ``` Desired output: ``` a b c ``` Actual output: ``` a b ``` Obviously the native forEach method doesn't check after each iteration whether the item has been deleted, so if it is then the next item is skipped. Is there a better way of doing this, aside from overriding the forEach method or implementing my own class to use instead of an array? Edit - further to my comment, I suppose the solution is to just use a standard for loop. Feel free to answer if you have a better way.