73

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • find the index of the object that has that id within your array and remove that from the array – juvian Dec 17 '15 at 14:11

3 Answers3

74

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

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
27

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);
udidu
  • 8,269
  • 6
  • 48
  • 68
6

can you try

newArray = myArr
  .filter(function(element) {
    return element.id !== thisId;
  });
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
David Faure
  • 1,336
  • 14
  • 25