How to remove a specific item from an array?

· · 2279 views

Is there an easy method to delete a particular element from an array? I'm searching for something like this:

array.remove(number);
0
2 Answers

Find the index of the array element you need to delete using indexOf, and afterward delete that index with splice.

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

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

Function removes only a single occurrence:

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

//Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))

Function removes all occurrences:

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}

//Usage
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
0

In this code example I use array.filter(...) function to remove unwanted items from an array.

Removing item from array (ECMA-262 Edition 5 code aka oldstyle JavaScript)

var value = 3

var arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(function(item) {
    return item !== value
})

console.log(arr)
// [ 1, 2, 4, 5 ]

Removing item (ECMAScript 6 code)

let value = 3

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => item !== value)

console.log(arr)
// [ 1, 2, 4, 5 ]

Removing multiple items (ECMAScript 7 code) An extra advantage of this technique is that you can delete multiple items.

let forDeletion = [2, 3, 5]

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!

console.log(arr)
// [ 1, 4 ]
0

Please login or create new account to participate in this conversation.