JavaScript - Remove specific element from an array

MarPlo
Posts: 88

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
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.

Adv. Posts: 01

Similar Topics