Insert & remove element at specific index of array in JavaScript

Overview

We can use the splice method to insert and remove an element at a specific array index.

Syntax

splice(start, noOfElementsToBeDeleted, ...elementsToInsert)
Syntax of spice method

Parameters

  • start: This is the index at which to start changing the array. If the index is negative, then the elements will be counted from the end of the array.
  • noOfElementsToBeDeleted: This denotes the number of elements to be removed from the array from the start. If we pass the value as 0, no elements will be removed.
  • ...elementsToInsert: These are the elements to be inserted into the array, beginning from the start. This is optional. If we only need to remove the elements from the array, then we can skip it.

Return value

This method returns the removed elements as an array. If no element is removed from the source array, it returns an empty array.

Example

let arr = [1, 2, 2, 3, 4, 6]
console.log("The array is :", arr)
//remove the element at index 2
arr.splice(2,1);// this will remove one element from the index 2
console.log("After remove the element at index 2 the array is : ", arr);
//insert an element at index 4
arr.splice(4,0, 5);// this will remove zero element from the index 4 and insert the element 5 at index 4
console.log("After inserting the element 5 at index 4 the array is : ", arr);

Explanation

  • Line 1: We create an array arr with 6 elements, [1,2,2,3,4,6].
  • Line 6: In our array, the element 2 is present twice at index 1 and 2. So let's remove the element 2 at index 2. We used the splice method with start as 2 because we need to remove the element from index 2 and noOfElementsToBeDeleted as 1 because we need to remove one element. This will delete the element at index 2 . Now the array is [1,2,3,4,6].
  • Line 11: Our array looks like the sequence of numbers from 1 to 6 but the element 5 is missing in the sequence. So let's add the element 5 at index 4. To add the element, we use the splice method with the start as 4 because we need to insert the element from index 4, noOfElementsToBeDeleted as 0 because we don't need to remove any element and elemetsToInserted as 5. This will insert the element 5 at index 4 . Now the array is [1,2,3,4,5,6].

Free Resources