Reputation: 131
I am pulling an object from firebase converting it to an array then doing remove element operation on it but there is some strange behaviour:
this.players = this.db.object('arena/players').valueChanges();
this.players.subscribe(players =>{
console.log(players);
this.playersarray= Object.keys(players).map(key => ({ key, value: players[key] }));
console.log(this.playersarray);
console.log(this.playersarray.length);
for(var i =0;i<this.playersarray.length;i++){
if(this.playersarray[i].value != "waiting"){
console.log(this.playersarray[i].value+"deleting");
this.playersarray.splice(i,1);
}
}
console.log(this.playersarray);
});
I am trying to remove elements which value are not equal to waiting.So in this case im expecting to remove engincan,lifesuxtr and get last console.log as only someotheruser,someuser but lifesuxtr is not removed ??? only engincan removed ?
Upvotes: 0
Views: 425
Reputation: 160
Simple way to remove array element by value.
var playersarray = {
"name": "John",
"age": 30,
"cars": "Ford"
};
for(value in playersarray){
if(playersarray[value] != "Ford"){
delete playersarray[value]; //deleting array elements if no 'Ford'
}
}
console.log(playersarray);
Output: {cars:"Ford"}
Upvotes: 0
Reputation: 449
When you remove the items from the array, the index of all following items shift down. Because you're removing an item, your loop skips an item.
// Array starts as:
// 0 1 2 3
// ['a', 'b', 'c', 'd']
// Loop 1: Index 0, item 'a'. Matches test, remove it.
// Array becomes:
// 0 1 2
// ['b', 'c', 'd']
// Loop 2: Index 1, item 'c'.
// Loop 3: Index 2, item 'd'.
The quickest fix is to change the index by subtracting one from it but that's can get hard to keep track of quickly. I'd recommend using the Array.filter() method.
this.playersarray = this.playersarray.filter(function(player) {
return player.value != 'waiting'
})
Upvotes: 0
Reputation: 35553
You can use Array.filter
operator to iterate over the Array and filter our the relevant results, example:
const arr = [1, 2, 3, 4, 5];
const result = arr.filter((item) => item % 2 === 1);
console.log(result);
Upvotes: 1