Remove elements from a JavaScript Array

You can use the arrayObject.filter() method to remove the item(s) from an array at specific index in JavaScript. The syntax for removing array elements can be given with:
arrayObject.filter(callback, contextObject);
The filter() method creates a new array with all the elements that pass the test implemented by the callback() function and it does not change the original array. Internally, the filter() method iterates over each element of the array and pass each element to the callback function. If the callback function returns true, it includes the element in the return array. examples
var rValue = 'three' var arrayItems = ['one', 'two', 'three', 'four', 'five', 'six'] arrayItems = arrayItems.filter(function(item) { return item !== rValue }) console.log(arrayItems)
Output:
[ 'one', 'two', 'four', 'five', 'six' ]

Using ECMAScript 6 code

var rValue = 'three' var arrayItems = ['one', 'two', 'three', 'four', 'five', 'six'] arrayItems = arrayItems.filter(item => item !== rValue) console.log(arrayItems)
Output:
[ 'one', 'two', 'four', 'five', 'six' ]

Using ECMAScript 7 code

let forDeletion = ['two', 'three', 'four'] var arrayItems = ['one', 'two', 'three', 'four', 'five', 'five' , 'six'] arrayItems = arrayItems.filter(item => !forDeletion.includes(item)) console.log(arrayItems)
Output:
[ 'one', 'five', 'six' ]

An additional advantage of above method is that you can remove multiple items from JavaScript array.


remove elements from Javascript array

Removing specific item suing splice()

You can also use the splice() method to remove the item from an array at specific index in JavaScript. This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. This means that splice() overwrites the original array.
splice(startIndex, deleteCount)
example
var arrayItems = ['one', 'two', 'three', 'four', 'five', 'five' , 'six'] console.log(arrayItems); const index = arrayItems.indexOf('five'); if (index > -1) { arrayItems.splice(index, 2); } console.log(arrayItems);
Output:
[ 'one', 'two', 'three', 'four', 'five', 'five', 'six' ] [ 'one', 'two', 'three', 'four', 'six' ]
In the above example, find the index of the array element you want to remove using indexOf(), and then remove that index with splice() method. The second parameter of splice() is the number of elements to remove.