Is there a method to remove an item from a JavaScript array?
Given an array:
var ary = ['three', 'seven', 'eleven'];
I would like to do something like:
removeItem('seven', ary);
I've looked into splice()
but that only removes by the position number, whereas I need something to remove an item by its value.
Really, i can't see why this can't be solved with
Or maybe you want to use vanilla JS
Please do not use the variant with
delete
- it makes a hole in the array as it does not re-index the elements after the deleted item.You can achieve this using Lodash
_.remove
function.This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.
To make it a global-
And to take care of IE8 and below-
I tried using the function method from jbaron above but found that I needed to keep the original array intact for use later, and creating a new array like this:
apparently creates by reference instead of value because when I removed an element from newArray the referenceArray also had it removed. So I decided to create a new array each time like this:
Then I use it like this in another function:
Now the vesselArr remains intact while each time I execute the above code the otherVessels array includes all but the latest vesselID element.