Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an object from a class array in javascript [duplicate]

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?

like image 429
SayMyName Avatar asked Sep 06 '25 11:09

SayMyName


1 Answers

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);
like image 161
Prasad Telkikar Avatar answered Sep 09 '25 02:09

Prasad Telkikar