How to remove a specific item from an array in JavaScript
Removing specific items from JavaScript arrays is crucial when building interactive applications that need to delete selected items, remove tags, or filter out unwanted data based on user actions.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented this functionality extensively in components like multi-select dropdowns, tag inputs, and data tables where users need to remove specific entries.
From my extensive expertise, the most reliable and efficient solution is combining indexOf()
to find the item’s position with splice()
to remove it.
This approach handles both primitive values and object references while maintaining array integrity.
Use indexOf()
to find the item’s index, then splice()
to remove it from the array.
const fruits = ['apple', 'banana', 'orange', 'banana']
const index = fruits.indexOf('banana')
if (index > -1) {
fruits.splice(index, 1)
}
// Result: ['apple', 'orange', 'banana']
The indexOf()
method searches for the first occurrence of the specified value and returns its index, or -1 if not found. The splice()
method then removes one element at that index position. In this example, indexOf('banana')
returns 1, and splice(1, 1)
removes one element at index 1. The condition if (index > -1)
ensures we only attempt removal if the item exists. Note that this removes only the first occurrence of the value.
Best Practice Note:
This is the same approach we use in CoreUI components for managing selected items and dynamic lists.
For removing all occurrences, use filter()
instead: fruits = fruits.filter(item => item !== 'banana')
. For complex objects, compare by specific properties rather than direct equality.