Remove specific item from an array in JavaScript

The JavaScript is a very powerful programming language and provides a great support for arrays. There are many different language constructs available that you can use to remove item from an array.

This article contains description of only the most popular ways to modify an array, but you can extend and improve them to meet your specific needs.

Changing length of an array

The first method that we are presenting is very simple and straightforward. You can remove some elements by assigning a specific value to the length property of an array.

In the example below, we change array size from 5 elements to 4 elements and after that the last item will be deleted.

var letters = ['a', 'b', 'c', 'd', 'e'];

letters.length = 4;

console.log(letters);

If you run the code provided above, the console output will look like this:

["a", "b", "c", "d"]

It's very important to note that this method is very flexible, since you can remove several elements at once. For example, you can also assign 1, 2 or 3 number to the length property, and the array will be resized accordingly.

Removing last item from an array

The Array class provides pop() method that deletes the last element from an array and returns it to the caller.

This is a convenient approach as you don't need to know what is the actual length of the array. The code will always work as long as there is some data in the given array.

var letters = ['a', 'b', 'c', 'd', 'e'];

letters.pop();

console.log(letters);

See console output after running the provided example:

["a", "b", "c", "d"]

Removing first item from an array

The shift() method is an opposite to the pop() method in a way that it deletes the first element from an array instead of the last. The value of the removed item is also returned to the caller.

var letters = ['a', 'b', 'c', 'd', 'e'];

letters.shift();

console.log(letters);

You may open console in browser and check the output after running our demo and there you will notice that the letter 'a' is not included in the array.

["b", "c", "d", "e"]

Using forEach() method

If you need to implement some custom and non standard logic, then you may use the forEach() method. It will run the given function only once for each item in the array.

Please review our code example below, which shows how to use the callback. There is an anonymous function that checks if the current array item equals to letter 'b'.

When comparison succeeds, the splice() method is called with two arguments, which are index of an element in the given array and count of items to delete.

var letters = ['a', 'b', 'c', 'd', 'e'];

letters.forEach(function(item, index, object) {
    if (item === 'b') {
        object.splice(index, 1);
    }
});

console.log(letters);

It's highly recommended that you run the code your self and see how it works. Also, you may see the console output below, the letter 'b' is missing since it was removed from the array in the demo.

["a", "c", "d", "e"]

Using regular "for" loop

The following method of removing array item is similar to what we've shown in the previous example. However, we are using the for loop instead of the forEach() method.

Withing the loop, we check if the current array item equals to letter 'b', and if yes, the splice() method is called accordingly.

Please pay attention that we have the "i--;" statement in the code. The loop index must be decremented since array length is decreased by one item after removing the element. If you remove more then one element, then the loop index, which is "i" in this sample, must be changed accordingly.

var letters = ['a', 'b', 'c', 'd', 'e'];

for (var i = 0; i < letters.length; i++) {
    if (letters[i] === 'b') {
        letters.splice(i, 1);
        i--;
    }
};

console.log(letters);

Please review the console output, which is shown after running the above code sample. As you'll notice, the letter 'b' is no longer in the array.

["a", "c", "d", "e"]

Using "while" loop

You may also use the while loop to iterate over the array of items. If current array element equals to letter 'b', then we call the splice() method with two parameters, which are index of an element and count of items to remove.

If the comparison statement does not succeed, then we have to increment the array index. You can see that in the "i++;" code line inside of the "else" block. This allows the while loop to process item correctly on the next iteration.

Please see how this method of removing an item is implemented in our code sample.

var letters = ['a', 'b', 'c', 'd', 'e'];

var i = 0;
while (i < letters.length) {
    if (letters[i] === 'b') {
        letters.splice(i, 1);
    } else {
        i++;
    }
};

console.log(letters);

The console output is provided below:

["a", "c", "d", "e"]

Creating custom JavaScript prototype

There is a design pattern that allows to avoid code duplication in your web application. If you need to remove array item in several places, then you can define a method on the constructor's prototype property and call it with just a single line anywhere in the code.

In the code block below, the "remove" method is created and it's assigned to the function that contains our algorithm with the while loop inside. The desired element will be removed with help of the splice() method.

Then, we call the remove() method on a target array with a single parameter, which is a value that has to be removed.

var letters = ['a', 'b', 'c', 'd', 'e'];

Array.prototype.remove = function(element) {
    var i = 0;
    while (i < this.length) {
        if (this[i] === element) {
            this.splice(i, 1);
        } else {
            i++;
        }
    };
}

letters.remove('b');

console.log(letters);

The console output is as the following, the 'b' array item is no longer in the array.

["a", "c", "d", "e"]

Using indexOf() method

We can simplify our searching algorithm by using the indexOf() method, which returns index of the element within a given array.

Then we can pass that index into the splice() method to remove desired element from the array. See how it is implemented in the code example below.

var letters = ['a', 'b', 'c', 'd', 'e'];

var index = letters.indexOf('b');

if (index > -1) {
    letters.splice(index, 1);
}

console.log(letters);

The 'b' element will be removed from the array and the console output should be like the following:

["a", "c", "d", "e"]

Using filter() method

You can also efficiently remove any element from the array by using the filter() method. It accepts a callback function as an argument, and there must be provided custom code that tests each element. You have to return true value if the specific element must be kept or false if skipped.

var letters = ['a', 'b', 'c', 'd', 'e'];

var filtered = letters.filter(function(value) {
    return value !== 'b';
})

console.log(filtered);

Please see the console output below:

["a", "c", "d", "e"]

Using filter() method and arrow function

This method is a modification of the example provided in previous section. The difference is that we are using the arrow function to filter out unneeded elements from the array. Such a design allows to make compact and clean code that is only one line length.

var letters = ['a', 'b', 'c', 'd', 'e'];

var filtered = letters.filter(value => value !== 'b');

console.log(filtered);

If you run the provided demo and open the console, you should see the following output:

["a", "c", "d", "e"]

Conclusion

As you have learned in this article, there many options that can be used to remove specific item from an array. But that's only the starting point, very likely you will need to adapt our code samples to meet your specific needs. You could extend the logic, for instance, to remove several elements at once or you may need to add support of complex multi-dimensional arrays, etc.

Thank you for reading this article, we encourage you to leave your notes or questions in the comment form below.

Leave a Reply

Your email address will not be published. Required fields are marked *