4

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
338k41 gold badges322 silver badges353 bronze badges
asked Feb 10, 2016 at 9:11

5 Answers 5

9

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;
});
answered Feb 10, 2016 at 9:12
Sign up to request clarification or add additional context in comments.

1 Comment

@Shanka Glad to help! :)
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));

answered Feb 10, 2016 at 9:17

Comments

0

Clear solution for your problem:

var newArr = arr.filter(function(el) { return el.id!= 2; }); 
console.log(newArr);
answered Feb 10, 2016 at 9:31

Comments

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);
answered Feb 10, 2016 at 10:25

Comments

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

answered Aug 26, 2022 at 16:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.