-6

My javascript code like this :

<script type="text/javascript">
    var clubs = [ 
        {id: 1, name : 'chelsea'},
        {id: 2, name : 'city'},
        {id: 3, name : 'liverpool'}
    ];
    if(clubs.indexOf(2) != -1)
        clubs.splice(2, 1)
    console.log(clubs)
</script>

For example, I want to delete the index with id = 2

I try like that, but it does not work. The index with id = 2 is not deleted

How can I solve this problem?

3

3 Answers 3

1

Here is a way to solve your problem, check this :

var clubs = [
  { id: 1, name: 'chelsea' },
  { id: 2, name: 'city' },
  { id: 3, name: 'liverpool' }
];

for (var i = 0; i < clubs.length; i++) {
  if (clubs[i].id == 2) {
    clubs.splice(i, 1);
    break;
  }
}

console.log(clubs);

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

2 Comments

Both way is fine . Yes using strictly typed is better . It cant be the reason to downvote. lol.Answer edited
Oh boy. Its javascript. . Its ok. Answer edited. Thanks for the reply
0

Use Array.filter

var clubs = [ 
        {id: 1, name : 'chelsea'},
        {id: 2, name : 'city'},
        {id: 3, name : 'liverpool'}
    ];

clubs = clubs.filter(function(item){
   return item.id !== 2;
});

console.log(clubs);

12 Comments

@downvoter - Reason please? What's the point of down-vote if the reason is not specified?
Why not point to one of the many duplicate questions instead of repeating a solution here? Plenty of solutions for this on SO.
@nikhilagw I think this is the only decent answer suggested. I didn't downvote it. But I think H77 is right.
It's the top answer here. Like I said.. plenty of duplicates. No reason to add more.
@nikhilagw Great. It works. Thanks a lot. I accept your answer and I voted for it. It's help me :)
|
0

The element is not getting deleted because of your if statement, you are checking if 2 is present or not in array, but there is nothing like 2 in array as it is an array of objects. So the condition always remains false.

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.