How can I remove a specific item from an array?

The Solution to How can I remove a specific item from an array? is


Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

_x000D_
_x000D_
const array = [2, 5, 9];_x000D_
_x000D_
console.log(array);_x000D_
_x000D_
const index = array.indexOf(5);_x000D_
if (index > -1) {_x000D_
  array.splice(index, 1);_x000D_
}_x000D_
_x000D_
// array = [2, 9]_x000D_
console.log(array); 
_x000D_
_x000D_
_x000D_

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

_x000D_
_x000D_
function removeItemOnce(arr, value) {_x000D_
  var index = arr.indexOf(value);_x000D_
  if (index > -1) {_x000D_
    arr.splice(index, 1);_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function removeItemAll(arr, value) {_x000D_
  var i = 0;_x000D_
  while (i < arr.length) {_x000D_
    if (arr[i] === value) {_x000D_
      arr.splice(i, 1);_x000D_
    } else {_x000D_
      ++i;_x000D_
    }_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
//Usage_x000D_
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))_x000D_
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
_x000D_
_x000D_
_x000D_

~ Answered on 2011-04-23 22:23:50


Most Viewed Questions: