Insert an Item at a Specific Index in JavaScript
In this tutorial, we will go through different ways to insert an item at a given index in an array, including both mutable and immutable approaches.
Method 1: Using splice()
The splice()
method is the classic way to insert an item at a specific position. It modifies the original array in place. You specify the index, how many items to remove (zero, if you're only inserting), and the new value to add.
const fruits = ["apple", "cherry"];
fruits.splice(1, 0, "banana");
console.log("Updated array:", fruits);
Updated array: ["apple", "banana", "cherry"]
Method 2: Using Slice and Spread (Immutable Approach)
If you're working in a context where mutating the original array is discouraged (like in React or functional programming), you can use slice()
and the spread operator to create a new array with the new item inserted.
const fruits = ["apple", "cherry"];
const index = 1;
const updatedFruits = [
...fruits.slice(0, index),
"banana",
...fruits.slice(index)
];
console.log("Original array:", fruits);
console.log("New array:", updatedFruits);
Original array: ["apple", "cherry"]
New array: ["apple", "banana", "cherry"]
Method 3: Manual Insertion Using Loop or Function
If you want full control or you're operating in a learning environment, you can write a custom function to insert an item manually. This approach can help you understand how array operations work under the hood.
function insertAt(array, index, value) {
return [...array.slice(0, index), value, ...array.slice(index)];
}
const fruits = ["apple", "cherry"];
const result = insertAt(fruits, 1, "banana");
console.log("Inserted array:", result);
Inserted array: ["apple", "banana", "cherry"]
When to Use Each Method
splice()
: Best when you're okay modifying the original array. Simple and efficient.- Slice + Spread: Perfect for immutability, like in Redux or React state updates.
- Custom function: Great for learning or building specialized behavior into your application.
Comments
Loading comments...