Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Sub Array Item in Javascript

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"
}]
like image 631
Shanka Avatar asked Oct 19 '25 11:10

Shanka


2 Answers

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;
});
like image 52
Rajaprabhu Aravindasamy Avatar answered Oct 21 '25 01:10

Rajaprabhu Aravindasamy


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));
like image 33
jcubic Avatar answered Oct 20 '25 23:10

jcubic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!