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.
I used the most voted option and created a function that would clean one array of words using another array of unwanted words:
To use, do the following:
The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.
arr is now ["red", "black", "white"]
You can use
without
orpull
from Lodash:You can use underscore.js. It really makes things simple.
For example, with this:
And
result
will be['three','eleven']
.In your case the code that you will have to write is:
It reduces the code that you write.
Here's a version that uses jQuery's inArray function:
a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete: