JavaScript Array Splice()
In this blog, we will discuss one of the versatile methods from JavaScipt which is Splice().
We normally have data in an array format and most of the time we need to manipulate these array by deleting, inserting or replacing it with a new element. Let’s see how Splice() works.
Syntax
Name_Of_Array.splice(index,delete_element, new_element_1, new_element_2,….);
· Name_Of_Array: Array name
· index: The starting point of Splice method(Array start with 0)
· delete_element: Number of elements should be deleted from index position
· new_element_1: New element that should be added/replaced by function.
Delete element
Here we are having an array with name arrayMonth. We are applying splice method at index 2 i.e on “Mar”(array start with 0) and we are deleting 1 element from it and returning an array with new data in it.
Output will be
Insert element
Now we are adding/inserting values at position 3 i.e after “Mar”. 0 indicates we are not deleting anything from the array, whereas “Apr” and “May” are values that we are going to insert.
Output will be
Replace element
In this example, we are starting from position 1 that is after “Jun” and deleting 2 elements from array and inserting 2 new elements at the same time. It is like deleting and adding simultaneously which occur as replacement feature.
Output will be
This is all about Splice(), one of the coolest functionalities in JavaScript which help us to manipulate array data.
Happy Coding. :)