Blog

How can I remove a specific item from an array in JavaScript?


Removing an item from an array in JavaScript

The idea of removing an item from an array in JavaScript can be daunting, but it doesn’t have to be. There are multiple ways to do so. Let’s take a look at a few of them.

Array.splice()

The Array.splice() function is often used to remove items from an array.
This is done by specifying the index position and the number of items to be removed.

Example
Let’s say we have the following array:


let array = ['John', 'Bill', 'Emma', 'Steve', 'Anne'];

To remove ‘Steve’ from the array we could write:


array.splice(3, 1);

This will remove 1 item starting from index position 3, which is ‘Steve’. After running this line of code, the array will now look like this:


['John', 'Bill', 'Emma', 'Anne']

Array.filter()

Another way to remove a specific item from an array is to use Array.filter().
It creates a new array by filtering out all elements that do not pass the test implemented by the provided function.

Example
Let’s say we have the same array as above:


let array = ['John', 'Bill', 'Emma', 'Steve', 'Anne'];

To remove ‘Steve’ from the array we could write:


let filtered = array.filter(item => item !== 'Steve');

This will create a new filtered array which consists of all elements from the original array except for ‘Steve’. After running this line of code, the filtered array will now look like this:


['John', 'Bill', 'Emma', 'Anne']

Additional methods

In addition to the two methods described above, there are a few more ways to remove specific items from an array. They include:

  • Array.pop() – removes the last element of an array
  • Array.shift() – removes the first element of an array
  • Array.shift() – removes the first element of an array
  • Array.shift() – removes the first element of an array

Each of these can be used to remove elements from an array in different situations.

Conclusion

Removing an item from an array in JavaScript doesn’t have to be an intimidating process. As you can see, it can be achieved in a few simple steps. Whether you use Array.splice(), Array.filter(), or some of the other alternatives, the process is relatively straightforward.

sa3dy

Mostafa Saady, Egyptian Software Engineer, supersonic self-learner and teacher, fond of learning and exploring new technologies and science. As a self-taught professional I really know the hard parts and the difficult topics when learning new or improving on already-known languages. This background and experience enables me to focus on the most relevant key concepts and topics.

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button