}

Javascript: How to remove a specific element from an array?

Created:

Introduction

Using array data structure is one of the basic knowledge you should learn to became a better javascript developer. In this small tutorial we are going to give examples on how to remove a particular element from an array using javascript.

We will se soe alternatives to solve this problem

Using ES2015

If you don't want to use ES2015, skip to the next section. On ES2015 it was introduced the filter method for arrays.

let remove_item = 3

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

items = items.filter(item => item !== remove_item)

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

Remeber that to use ES2015 syntax in old browsers you can use BabelJS.

Using indexOf and Splice (old javascript)

indexOf first parameter is the elment to search in the array. The method will return the index (int) or -1 if the element was not found. splice add or removes elements from the array and returns the removed elements. The first parameter is the index and the second one is the amount of elements to remove from the index.

var elements = [1,2,3,4,5,6,7,8,9,10];
var element_index = array.indexOf(5);
// we check if the elements was found
if (element_index > -1) {
  //we delete only one element from the index position
  elements.splice(index, 1);
}

Custom function to remove all occurences

If in you code you need to delete an item it could be a good idea to write a function to remove it. Here is the body of the function:

function remove(arr, item) {
    for (var i = arr.length; i--;) {
        if (arr[i] === item) {
            arr.splice(i, 1);
        }
    }
}

As you can see the idea is very similar than the previous one. But in this case it will delete all occurences of the item in the array.