Greg Gum Greg Gum - 4 months ago 8
Javascript Question

How to remove an object from an array without returning a new array while using native javascript

I have an array of objects such as Id:1, Name:Greg

Now I need to remove the object with an Id of 5.

I just need the existing array with the item removed, not a new array.

I don't want to use an external library to do this.

(The suggested duplicate answer is for deleting a number of objects at once, which is not what I want to do.)

What I would like to do is call

remove(theArray, theObject);


and it would remove it from the array.

Answer

Look into array.splice method. You can pass it the index if object and 1 for delete count. This modifies the original array.

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

array.splice(start, deleteCount[, item1[, item2[, ...]]])

var index = items.indexOf(itemToFind);
items.splice(index, 1);