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?
asked Apr 11, 2018 at 4:58
moses toh
13.3k82 gold badges266 silver badges460 bronze badges
3 Answers 3
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);
H77
5,9772 gold badges29 silver badges40 bronze badges
answered Apr 11, 2018 at 5:16
Insanity Geek
1571 silver badge13 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Insanity Geek
Both way is fine . Yes using strictly typed is better . It cant be the reason to downvote. lol.Answer edited
Insanity Geek
Oh boy. Its javascript. . Its ok. Answer edited. Thanks for the reply
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);
answered Apr 11, 2018 at 5:02
Nikhil Aggarwal
28.5k4 gold badges46 silver badges61 bronze badges
12 Comments
Nikhil Aggarwal
@downvoter - Reason please? What's the point of down-vote if the reason is not specified?
H77
Why not point to one of the many duplicate questions instead of repeating a solution here? Plenty of solutions for this on SO.
Aluan Haddad
@nikhilagw I think this is the only decent answer suggested. I didn't downvote it. But I think H77 is right.
moses toh
@nikhilagw Great. It works. Thanks a lot. I accept your answer and I voted for it. It's help me :)
|
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
Explore related questions
See similar questions with these tags.
lang-js
2. Have a look here for solutions.