Delete a member of an array

By | September 19, 2012

Here’s a quickie: Need to delete a member of an array in JavaScript? The traditional way is with the splice() method. Here’s an alternative using filter():

var deleteFromArray = function(array, valToRemove) {
   return array.filter(function(member) {
      return member !== valToRemove;

Demonstrated in the JavaScript console:

The filter() method examines each member of your array and applies the function you pass as its argument. In this case, our function returns the member only when it doesn’t match the value we want to remove. You could also use filter() to manipulate each array member in another way, say to multiply by some value.