The usual solution for mutating the current array is to use a for
loop and do the iteration from backwards to front:
var arr = [{id:"231"}, {id:"343"}];
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i].id === "231") {
arr.splice(i, 1);
}
}
console.log(JSON.stringify(arr));
This way, when you splice()
out the current item, you are only changing the indexes of array elements that you have already visited and the iteration is not affected.
It's also possible to run the for
loop from start to finish and just correct the index value after splicing out an element.
var arr = [{id:"231"}, {id:"343"}];
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i].id === "231") {
arr.splice(i, 1);
}
}
console.log(JSON.stringify(arr));
Keep in mind that a plain for
loop always gives you more control over the iteration than a .forEach()
loop since you can break
, continue
or modify the iteration index at any time, things which you cannot do with .forEach()
.
If you're OK with the end result being a new array, then .filter()
would work quite easily for you as this is what it is built for.
var arr = [{id:"231"}, {id:"343"}];
arr = arr.filter(function(item) {
return item.id !== "231";
});
console.log(JSON.stringify(arr));
Or, in ES6:
var arr = [{id:"231"}, {id:"343"}];
arr = arr.filter(item => item.id !== "231");
console.log(JSON.stringify(arr));