One of the common scenarios that a JavaScript developer comes across while developing web applications is how to remove an element from JavaScript array. The task to remove an element from JavaScript array can be accomplished in a number of of ways.

In this tutorial, you’ll see a list of different methods to remove an element from JavaScript array.

Other tutorials in JavaScript Array series.

Use splice To Remove An Element From JavaScript Array

You can make use of the splice method to remove an element from JavaScript array. splice method when applied on an array, mutates the array and returns the removed elements. Let’s see how you can use splice to remove element from an array.

To remove elements using splice method, you first need to find the index of the element to be removed from the array. Once you have the index of the element to be removed from the array, you can use splice method to remove the element from the array. Here is how the code looks :

var arr = [1,2,3,4,5]
var element_to_be_removed = 4
var index = arr.indexOf(4)
var removed_element = arr.splice(index, 1)
console.log('element removed is ', removed_element)
console.log('resulting array is ', arr)

The above code would return the following output :

"element removed is " [4]
"resulting array is " [1, 2, 3, 5]

You can even convert the above code into a Array prototype function which can be applied on a JavaScript array. Create an Array.prototype function as shown which will return the array after removing the element. Here is how the code looks :

Array.prototype.remove = function(elem) {
  var index = this.indexOf(elem)
  var removed_element = this.splice(index, 1)
  return this
}

console.log([1,5,10].remove(10))

The above code will return the below output :

// output 
[1, 5]

Use filter To Remove An Element From JavaScript Array

You can make use of the JavaScript array filter method to remove an element from JavaScript array. JavaScript filter method returns a new array and doesn’t mutate the existing array.

var arr = [1,2,3,4,5]
var remove_item = 4
var filtered_arr = arr.filter(function(item){
  return item!=remove_item
})
console.log(filtered_arr)

The above code will return the following output :

// output
[1, 2, 3, 5]

Wrapping It Up

In this tutorial, you saw how to remove an element from JavaScript array using JavaScript splice and filter methods. Have you used any other approach to remove an element from JavaScript array ?

Do let us know your thoughts in the comments below.