77

I have an array of objects:

var myArr; 

Let’s say that on page load it contains 10 objects with the following structure:

{ Id: …, Name: … } 

How can I remove an object from myArr by its Id?

1
  • find the index of the object that has that id within your array and remove that from the array Commented Dec 17, 2015 at 14:11

3 Answers 3

78

Try like this

var id = 2; var list = [{ Id: 1, Name: 'a' }, { Id: 2, Name: 'b' }, { Id: 3, Name: 'c' }]; var index = list.map(x => { return x.Id; }).indexOf(id); list.splice(index, 1); console.log(list); 

JSFIDDLE

Or you can utilize .filter()

Like this

var id = 2; var list = [{ Id: 1, Name: 'a' }, { Id: 2, Name: 'b' }, { Id: 3, Name: 'c' }]; var lists = list.filter(x => { return x.Id != id; }) console.log(lists); 

DEMO

Sign up to request clarification or add additional context in comments.

Comments

29

Two solutions, one evolve creating new instance and one changes the instance of your array.

Filter:

idToRemove = DESIRED_ID; myArr = myArr.filter(function(item) { return item.Id != idToRemove; }); 

As you can see, the filter method returns new instance of the filtered array.

Second option is to find the index of the item and then remove it with splice:

idToRemove = DESIRED_ID; index = myArr.map(function(item) { return item.Id }).indexOf(idToRemove); myArr.splice(index, 1); 

Comments

7

can you try

newArray = myArr .filter(function(element) { return element.id !== thisId; }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.