Code Logo

Insert with Array.splice()

Published at25 Jul 2026
JavaScript Data Structures Medium 0 views
Like0

Write a JavaScript function that uses Array.splice() to insert or remove elements at a specific index in an array. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

The splice() method takes three parameters: the start index, the number of elements to remove (deleteCount), and the elements to insert. When deleteCount is 0, no elements are removed and the new elements are inserted at the start position. When deleteCount is greater than 0, that many elements starting at start are removed and the new elements are inserted in their place.

Unlike slice() which returns a portion of an array without modifying it, splice() mutates the original array directly and returns the deleted elements. This in-place mutation is a distinctive feature of splice() that makes it powerful but requires careful use. Understanding splice() is essential for managing dynamic collections in JavaScript.

Time complexity is O(n) where n is the array length after the operation, as elements may need to be shifted to accommodate the changes. Space complexity is O(k) where k is the number of deleted elements (returned as a new array).

Edge cases include negative start indices (count from end of array), start beyond array length (insert at end), deleteCount larger than remaining elements (remove all until end), and inserting multiple elements at once.

Example Input & Output

Example 1
Input
[1,2,3],3,0,4
Output
[1,2,3,4]
Explanation

Append 4 at end

Example 2
Input
[1,2,3,4,5],0,0,0,0
Output
[0,0,1,2,3,4,5]
Explanation

Prepend two zeros

Example 3
Input
[1,2,3,4,5],2,0,99
Output
[1,2,99,3,4,5]
Explanation

Insert 99 at index 2, remove 0

Example 4
Input
[1,2,3,4],1,1
Output
[1,3,4]
Explanation

Remove element at index 1

Example 5
Input
[1,2,3,4,5],1,2
Output
[1,4,5]
Explanation

Remove 2 elements starting at index 1

Algorithm Flow

Recommendation Algorithm Flow for Insert with Array.splice()
Recommendation Algorithm Flow for Insert with Array.splice()

Solution Approach

Insert elements into an array at a specific index using splice(). This method modifies the array in place by removing or replacing existing elements and/or adding new elements. The first parameter is the start index, the second is the delete count (0 for insert only), and the rest are elements to add.

function solution(arr, idx, v) { arr.splice(idx, 0, v); return arr; }

splice() returns an array of removed elements. For insertion with deletion: splice(idx, deleteCount, v). To remove elements without insertion: splice(idx, deleteCount).

Time O(n), Space O(1).

Best Answers

javascript - Approach 1
function solution(arr, start, deleteCount, ...items) {
  arr.splice(start, deleteCount, ...items);
  return arr;
}