Remove an Item From a Specific Position in JavaScript
In JavaScript, this can be done in several ways—some modify the original array, while others return a new one. In this tutorial, we’ll walk through different methods to remove an item at a specific index in an array in JavaScript, with examples and explanation.
Method 1: Using splice()
(Mutable)
The splice()
method allows you to remove or replace elements from any position. This method modifies the original array in place.
const fruits = ["apple", "banana", "cherry"];
const removed = fruits.splice(1, 1);
console.log("Updated array:", fruits);
console.log("Removed item:", removed[0]);
Updated array: ["apple", "cherry"]
Removed item: banana
Method 2: Using filter()
(Immutable)
Want to remove an item without changing the original array? filter()
lets you create a new array by excluding items based on a condition. This is an excellent approach when working with immutable data patterns such as in React or Redux.
const fruits = ["apple", "banana", "cherry"];
const indexToRemove = 1;
const newFruits = fruits.filter((_, index) => index !== indexToRemove);
console.log("Original array:", fruits);
console.log("New array:", newFruits);
Original array: ["apple", "banana", "cherry"]
New array: ["apple", "cherry"]
Method 3: Using slice()
and Spread Operator
Another non-mutating approach involves combining slice()
and the spread operator to rebuild the array while skipping the item at the target index.
const fruits = ["apple", "banana", "cherry"];
const indexToRemove = 1;
const newFruits = [...fruits.slice(0, indexToRemove), ...fruits.slice(indexToRemove + 1)];
console.log("Original array:", fruits);
console.log("New array:", newFruits);
Original array: ["apple", "banana", "cherry"]
New array: ["apple", "cherry"]
Which Method Should You Choose?
splice()
: Great for direct manipulation and quick operations when mutating the original array is acceptable or required.filter()
: Ideal for clean and readable code, especially in functional or reactive paradigms where immutability is important.slice()
+ Spread: A balanced approach offering clarity and immutability without functional callbacks.
Comments
Loading comments...