0

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);


  });

This is console: enter image description here

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 ?

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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'
})

Comments

0

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.