Quick answer: find the index with indexOf, then remove it with
splice:
const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // removes 1 element at that index
}
// array is now [2, 9]

Removing by value without mutating the original array
const array = [2, 5, 9];
const filtered = array.filter(item => item !== 5);
// filtered = [2, 9]; the original `array` is unchanged
filter is the go-to choice in modern JS when you want an immutable update (common in React
and other frameworks that rely on reference-equality checks).
Removing by index directly
array.splice(index, 1); // remove 1 item starting at `index`
Removing every occurrence of a value
const array = [1, 5, 2, 5, 3];
const withoutFives = array.filter(item => item !== 5);
// [1, 2, 3]
indexOf + splice only removes the first match; loop it or use
filter if the value can appear more than once.
FAQ
Does splice mutate the original array?
Yes. splice changes the array in place and returns the removed elements. Use
filter instead if you need the original array left untouched.
What if indexOf returns -1?
That means the value isn't in the array. Always guard with if (index > -1) before calling
splice, otherwise splice(-1, 1) removes the last element instead of
doing nothing.
What's the fastest way for large arrays?
For very large arrays where order doesn't matter, swapping the target element with the last one and
popping is O(1); for typical app-sized arrays, splice or filter are simpler and
fast enough.
This article explains and expands on the community answers to the Stack Overflow question “How can I remove a specific item from an array in JavaScript?”, used under the CC BY-SA 4.0 license. Screenshot credit: Stack Exchange Inc.
No comments
Post a Comment