I am trying to remove an object from an array if a particular value for a key matches a given string:
Example data:
array = [{_id: "abc", test: "123"},
{_id: "def", test: "123"},
{_id: "ghi", test: "123"}];
Here is my loop:
for (var i = 0; i < array.length; i++) {
var x = "123"
if (array[i].test == x) {
array.splice(i, 1)
}
}
This should return an empty array but it's leaving one object in the array (the last one) and I've got no clue why.
for ( var i = array.length; i--; ). That works because when you remove an element only the indices of elements past that one are affected; elements before it are not touched, so if you are iterating backwards, removing an element won't affect the index of future elements in your loop.