How to insert an item into an array at a specific index in JavaScript?

To insert an item into an array at a specific index in JavaScript, you can use one of the following methods:

1. Using splice() (Modifies Original Array)

The splice() method modifies the original array by adding/removing elements at a specific index.

const array = [1, 2, 3, 4];
const index = 2;   // Insert at position 2 (0-based)
const newItem = 99;

// Insert without removing any elements (deleteCount = 0)
array.splice(index, 0, newItem);

console.log(array); // Output: [1, 2, 99, 3, 4]

Parameters:

  • index: Position to insert.
  • 0: Number of elements to remove (set to 0 for pure insertion).
  • newItem: The item to insert.

2. Using Spread Syntax (Creates a New Array)

Create a new array without modifying the original by combining slices before and after the insertion point:

const originalArray = [1, 2, 3, 4];
const index = 2;
const newItem = 99;

const newArray = [
  ...originalArray.slice(0, index),
  newItem,
  ...originalArray.slice(index)
];

console.log(newArray); // Output: [1, 2, 99, 3, 4]

3. Insert at the Beginning or End

Use unshift() or push() for edge cases:

// Insert at the start
array.unshift(newItem); 

// Insert at the end
array.push(newItem);

Key Notes

MethodMutates Original?Use Case
splice()✅ YesIn-place modification
Spread Syntax❌ NoImmutable operations (e.g., React)

Edge Cases

  • Index > Array Length: The item is added at the end.
  array.splice(10, 0, newItem); // Adds to end if array length < 10
  • Negative Index: Use array.length + negativeIndex for offset-from-end logic.

Example Function

function insertItem(arr, index, newItem) {
  return [...arr.slice(0, index), newItem, ...arr.slice(index)];
}

// Usage
const updatedArray = insertItem([1, 2, 4], 2, 3);
console.log(updatedArray); // [1, 2, 3, 4]

Result:
Choose splice() for direct modification or spread syntax for immutability!

Leave a Reply

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