I am using splice to remove an element from an array, but it's not working. as far as I know, the code looks okay , but maybe I am missing/overseeing something. please take a look. here 'state' is an array containing objects.
let removeFromState = state;
for(var i=0;i<removeFromState.length;i++){
if(removeFromState[i].index===action.index){
removeFromState.splice[i,1];
}
}
return removeFromState;
I cant believe, i was being so silly. and i had been looking at it for quite a while but didnt see it right in front of me. but I am glad i posted it here, because of the remarks about missing entries because I was increasing 'i' even though I was removing entries.
There are two issues:
A typo, you're using [i,1]
(square brackets) where you should be using (i,1)
(parentheses). Square brackets are property accessors. (The reason this isn't a syntax error is that JavaScript has a comma operator, and [i,1]
evaluates to [1]
. The reason it's not a runtime error is that functionname[1]
looks up the property "1"
on the function — and then disregards any value it finds.)
Your loop will skip entries after the entries it removes, because you both remove the entry and increase i
. So when you remove entry #5, entry #6 becomes #5 — but then you move on to i == 6
. So you never look at the new entry #5.
To fix #2, either only increase i
if you don't remove the entry, or loop backward.
So either:
var i = 0;
while (i < removeFromState.length) {
if(removeFromState[i].index === action.index) {
removeFromState.splice(i, 1);
} else {
++i;
}
}
or
for (var i = removeFromState.length - 1; i >= 0; --i) {
if(removeFromState[i].index === action.index) {
removeFromState.splice(i, 1);
}
}
Or alternately, create a new array containing only the entries you want to keep:
var newArray = removeFromState.filter(function(entry) { return entry.index !== action.index; });