Mdb
Mdb

Reputation: 8568

Javascript: Remove an element from an array of objects

I have an array of objects:

var items = [{ id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3"}];

I have the following object:

var itemToRemove = { id: 2, text: "test2" };

I want to check by id if itemToRemove exists in the items array.

And remove it:

  // pseudo code
  items.remove(itemToRemove);

I went through javascript array methods but found nothing that will do the job. Thanks!

Upvotes: 1

Views: 173

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74204

Use filter:

items.filter(function (item) {
    return item.id !== 2 || item.text !== "text2";
});

It's generally not a good idea to mutate the original array or else I would recommend Sirko's answer. The filter method produces a whole new array. It doesn't mutate the original array.

Upvotes: 2

Sirko
Sirko

Reputation: 74036

Traverse the array by using a plain loop and then remove the matching item by using splice():

for( var i=0; i<items.length; i++ ) {
  if( items[i].id == itemToRemove.id ) {
    items.splice( i, 1 );  // remove the item
    break; // finish the loop, as we already found the item
  }
}

Upvotes: 1

Related Questions