3

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"
}]
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Shanka
  • 811
  • 1
  • 7
  • 16

5 Answers5

8

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;
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

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));
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

Clear solution for your problem:

var newArr = arr.filter(function(el) { return el.id!= 2; }); 
console.log(newArr);
kostova
  • 61
  • 4
0

This is how I have done it

    var toRemove = "2";
    var toKeep = [];
    var arr = [ {"id":1,"name":"Steve"} , {"id":2,"name":"Martin"} , {"id":3,"name":"Short"} ];

    var listOfItems = JSON.stringify(arr);

    var splitItems = listOfItems.split('},');

    for(var i = 0; i< splitItems.length; i++){

    var details = splitItems[i].split(',');

    if(details[0].split(':')[1] !== toRemove){

    var people = {id:details[0].split(':')[1], name:details[1].split(':')[1].replace('}]', '')};

    toKeep.push(people);

    }


    }

    console.log(toKeep);
BestCod3r
  • 27
  • 2
0

In my case, I wanted to subtract one array from the other. So exclude a sub array from another where items are complex objects (with id field for example).

For non complex arrays, you can use the answer here: https://stackoverflow.com/a/53092728/2394052

Otherwise, for more complex objects, you can use:

    const fullArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
    const subArray = [{ id: 1 }, { id: 3 }];
    const resultArray = fullArray.filter(
        (x) => !subArray.find((x2) => x.id === x2.id)
    );

So, this basically says, give me back the items that are not present in subArray

Stephane
  • 11,056
  • 9
  • 41
  • 51