JavaScript - Remove specific element from an array

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
MarPlo
Posts:186

JavaScript - Remove specific element from an array

I have an array of integers:

Code: Select all

var array = [2, 5, 9, 8];
Is there a simple way to remove a specific element from an array? The equivalent of something like:

Code: Select all

array.remove(item);
I have to use pure JavaScript - no frameworks.

Admin Posts:805
Use the indexOf() to find the index of the element you want to remove, then apply splice() to remove it:

Code: Select all

var array = [2, 5, 9, 8];
var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
console.log(array);  // [2, 9, 8]
- The second parameter of splice() is the number of elements to remove.
- splice() modifies the array in place and returns a new array containing the elements that have been removed.

Note: indexOf() is not supported in IE7-8.

drakebohan Posts:1
You can use the arrayObject.filter() method :
net-informations.com/js/progs/remove.htm

Example, remove 1 specific item:

Code: Select all

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

Code: Select all

[ 'one', 'two', 'four', 'five', 'six' ]

Example, remove multiple items:

Code: Select all

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:

Code: Select all

[ 'one', 'five', 'six' ]

Similar Topics