I have this array containing simple objects
var data = [
{type:1, owner:"jason"},
{type:1, owner:"john"},
{type:2, owner:"jason"},
{type:2, owner:"alice"},
{type:2, owner:"bob"},
{type:2, owner:"clark"},
{type:1, owner:"david"}
]
i am trying to loop through the array and removing only elements with type:1. This is what i tried.
for(var i = 0; i < data.length; i++){
if(data[i].type === 1){
data.splice(i,1)
}
}
Would it be stupid of me to assume that after that loop runs that all type 1 elements will be removed from the array. After running this in chrome dev tools, the array still contains {type:1, owner:"jason"} and all type:2's were left untouched as expected. what am i doing wrong?
3 Answers 3
You have to just decrement i after splice
i--;
BTW I would like to just use filter and assign result to same data variable like bellow
data = data.filter(function(obj) {
return obj.type !== 1;
})
console.log(data);
1 Comment
you should run i-- after splice, because splice resize the array,the array index immediately changed after removing.
for(var i = 0; i < data.length; i++){
if(data[i].type === 1){
data.splice(i,1);
i--;
}
}
Decrease i by 1 whenever you splice your var data. Because that means the array list of objects is becoming smaller and so the index position shifts.
Since you aren't decreasing by 1, you start with the jason at position 0 and then directly jump to jason at position 2. WHY does this happen? Since you sliced an object in the beginning, your index position shifted like this.
First loop: i=0
var data = [
{type:1, owner:"jason"},//position 0
{type:1, owner:"john"},//position 1
{type:2, owner:"jason"},//position 2
{type:2, owner:"alice"},//position 3
{type:2, owner:"bob"},//position 4
{type:2, owner:"clark"},//position 5
{type:1, owner:"david"}//position 6
]
Second loop i=1
var data = [
{type:1, owner:"jason"},//SPLICED
{type:1, owner:"john"},// position 0
{type:2, owner:"jason"}, //position 1
{type:2, owner:"alice"},// position 2
{type:2, owner:"bob"},//position 3
{type:2, owner:"clark"},//position 4
{type:1, owner:"david"}//position 5
]
1 Comment
Explore related questions
See similar questions with these tags.