How would I remove the whole sub array item from the following array where id = 2
in JavaScript/jQuery?
arr = [{
"id": 1,
"name": "Steve"
},{
"id": 2,
"name": "Martin"
},{
"id": 3,
"name": "Short"
}]
I am not sure how to use grep
or splice
in this situation.
My desired output would be:
newArr = [{
"id": 1,
"name": "Steve"
},{
"id": 3,
"name": "Short"
}]
Try to use Array.prototype.filter
at this context,
var arr = [ {"id":1,"name":"Steve"} , {"id":2,"name":"Martin"} , {"id":3,"name":"Short"} ];
var newArr = arr.filter(function(itm){
return itm.id !== 2;
});
You can iterate over array and use splice when you find id
var arr = [{"id": 1,"name": "Steve"},{"id": 2,"name": "Martin"},{"id": 3,"name": "Short"}];
for (var i=0; i<arr.length; ++i) {
if (arr[i].id == 2) {
arr.splice(i, 1);
}
}
alert(JSON.stringify(arr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With