1

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!

Mdb
  • 7,538
  • 20
  • 58
  • 94
  • Possible duplicate of [How to remove item from array by value?](https://stackoverflow.com/questions/3954438/how-to-remove-item-from-array-by-value) – pscl Dec 14 '17 at 00:37
  • Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Aluan Haddad Apr 11 '18 at 05:44

2 Answers2

2

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.

Aadit M Shah
  • 67,342
  • 26
  • 146
  • 271
  • +1, but this won't work in crappy (i.e., IE < 9) browsers. You'd have to use some kind of a shim to [add the filter method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to the Array object. – Robusto Sep 23 '13 at 11:56
  • @Robusto `if (![].filter) Array.prototype.filter = function (callback, that) { var index = 0, length = this.length, list = []; while (index < length) { var item = this[index]; if (callback.call(that, item, index++, this)) list.push(item); } return list; };` – Aadit M Shah Sep 23 '13 at 12:07
1

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
  }
}
Sirko
  • 65,767
  • 19
  • 135
  • 167