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?

2
  • use filter to remove it? Commented Dec 10, 2018 at 11:02
  • 1
    You are asking 2 questions. First - is how to find an Object in an Array by key/value. Second - How to remove an item from an array. Commented Dec 10, 2018 at 11:06

3 Answers 3

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

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

4 Comments

Thanks, it worked. Now I have one more question. If I add any method to snake class like 'moveRight()', can I call the method for a specific snake.
For example, snakeList.filter(x => x.id == 22).moveRight();
if(snakeList.filter(x => x.id == 22).length){ moveRight();}
Okay sorry for my second question. Also, thank you for your answer.
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.