4

I have a javascript class like,

class Snake{
    constructor(id, trail){
        this.velocityX = 0;
        this.velocityY = -1;
        this.trail = trail;
        this.id = id;
    }
    moveRight(){
        console.log('move');
    }
}

and an array that stores Snake objects.

this.snakeList = new Array();
this.snakeList.push(new Snake(10, newSnakeTrail));
this.snakeList.push(new Snake(20, newSnakeTrail));
this.snakeList.push(new Snake(30, newSnakeTrail));
this.snakeList.push(new Snake(22, newSnakeTrail));
this.snakeList.push(new Snake(40, newSnakeTrail));

For example, I want to remove the element from the array which id is 20.

How can I do that?

SayMyName
  • 461
  • 5
  • 17

3 Answers3

5

What about this

this.snakeList = this.snakeList.filter(x => x.id != 20);

let snakes = [{name: 'fuss', id: 10}, {name: 'huss', id: 20}, {name: 'hurr', id: 60}]
//Before removal
console.log("Before removal");
console.log(snakes);

snakes = snakes.filter(x => x.id != 20);

//After removal
console.log("After removal");
console.log(snakes);
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

var snakeList = [
{
id:10,
trail:{}
},
{
id:20,
trail:{}
},
{
id:30,
trail:{}
}
]

snakeList.forEach((x,index)=>{

if(x.id === 20){
snakeList.splice(index,1)
}
})

console.log(snakeList)

See this is the working example hope this helps

siddharth shah
  • 1,139
  • 1
  • 9
  • 17
-1

I'd use splice here:

for (var i = 0; i < snakes.length; i++) {
    var obj = snakes[i];
    if (obj.id === 20) {
        snakes.splice(i, 1);
        i--;
    }
}

Snippet:

let snakes = [{name: 'fuss', id: 10}, {name: 'huss', id: 20}, {name: 'hurr', id: 60}]

for (var i = 0; i < snakes.length; i++) {
    var obj = snakes[i];
    if (obj.id === 20) {
        snakes.splice(i, 1);
        i--;
    }
}

console.log(snakes)
Barr J
  • 10,636
  • 1
  • 28
  • 46