Remove Item from Array in JavaScript

Remove a Specific Item from an Array in JavaScript

Estimated reading time: 2 minutes

Removing specific items from an array in JavaScript is a common task, yet JavaScript doesn’t offer a simple .remove() method. This guide covers multiple ways to remove items using core JavaScript functions like splice and filter. We’/sepll also include code snippets and examples to help you choose the best approach for your use case.


TL;DR

To remove a specific item from an array in JavaScript:

  • Use splice for index-based removal.
  • Use filter for functional removal based on values.

Removing an Item by Index with splice

The splice method is ideal if you know the index of the item you want to remove.

Syntax

Here, index is the position of the item, and 1 specifies that only one item should be removed.

Example:

To remove 5 from an array:

Note: splice modifies the original array.


Wrapping it in a function

For situations where you want to remove only the first occurrence of a specific value, you can wrap splice in a function.

Example:


Removing All Occurrences by Value

To remove all instances of a specific value, use a loop that checks for the value at each index.

Example:


Functional Approach with filter

If you prefer a functional approach that doesn’t modify the original array, use filter.

Example:

This method creates a new array excluding the specified value, making it useful in functional programming contexts.


Additional Tips

  1. Avoid delete: Using delete on array elements only removes the value but leaves an empty slot, causing unexpected behavior.
  2. Use indexOf for Checking: Always check for the presence of an item before using splice, as indexOf returns -1 if the item is not found.

  1. Stack Overflow: How can I remove a specific item from an array in JavaScript?
  2. MDN Web Docs: Array.prototype.splice()
  3. MDN Web Docs: Array.prototype.filter()
  4. MDN Web Docs: Array.prototype.indexOf()

Leave a Reply

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