Shanka
Shanka

Reputation: 821

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"
}]

Upvotes: 4

Views: 16149

Answers (5)

Steph
Steph

Reputation: 12202

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

Upvotes: 0

BestCod3r
BestCod3r

Reputation: 27

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);

Upvotes: 0

kostova
kostova

Reputation: 61

Clear solution for your problem:

var newArr = arr.filter(function(el) { return el.id!= 2; }); 
console.log(newArr);

Upvotes: 0

jcubic
jcubic

Reputation: 66490

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));

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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;
});

Upvotes: 9

Related Questions