Insert with Array.splice()
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
Append 4 at end
Prepend two zeros
Insert 99 at index 2, remove 0
Remove element at index 1
Remove 2 elements starting at index 1
Algorithm Flow

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.
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
function solution(arr, start, deleteCount, ...items) {
arr.splice(start, deleteCount, ...items);
return arr;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
