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 thestart. If we pass the value as0, 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 2arr.splice(2,1);// this will remove one element from the index 2console.log("After remove the element at index 2 the array is : ", arr);//insert an element at index 4arr.splice(4,0, 5);// this will remove zero element from the index 4 and insert the element 5 at index 4console.log("After inserting the element 5 at index 4 the array is : ", arr);
Explanation
- Line 1: We create an array
arrwith 6 elements,[1,2,2,3,4,6]. - Line 6: In our array, the element
2is present twice at index1and2. So let's remove the element2at index2. We used thesplicemethod withstartas2because we need to remove the element from index2andnoOfElementsToBeDeletedas1because we need to remove one element. This will delete the element at index2. Now the array is[1,2,3,4,6]. - Line 11: Our array looks like the sequence of numbers from
1to6but the element5is missing in the sequence. So let's add the element5at index4. To add the element, we use thesplicemethod with thestartas4because we need to insert the element from index4,noOfElementsToBeDeletedas0because we don't need to remove any element andelemetsToInsertedas 5. This will insert the element5at index4. Now the array is[1,2,3,4,5,6].