In this section, we will learn what the Array splice() method is and how to use it in JavaScript.
JavaScript Arrays splice() Method
The splice() method is used for adding and removing elements within the body of an array.
You see, for adding or removing elements from the start or end side of an array, we can use methods like pop(), push(), shift(), and unshift().
But when it comes to working with elements inside an array, we can’t use those mentioned methods anymore!
This is where the splice() method is specialized for!
Depending on how we set the arguments of this method, it is capable of adding elements within the body of an array, removing elements, and also running both operations at the same time if needed!
Array splice() Syntax:
arrayObject.splice(index, howMany, element1, element2, …element_N);
Array splice() Method Parameters:
`index`: This is the index number from which the adding/removing elements should begin.
`howMany`: Via the `splice` method, we can remove elements of an array. This second argument specifies how many elements should be deleted starting at the position of `index`. If the value is set to 0, that means no elements should be removed.
Note: This value is optional and can be ignored. If this argument is set to 0, that means we only want to add new elements to an array without deleting any already existing element.
`element1, element2, …element_N`: These are the elements that we specify to be added to the target array.
Note: element1… element_N are optional and can be ignored. If we don’t add any element, that means the operation of the spilce() method is to remove elements only.
Array splice() Method Return Value:
The returned value of this method is either an empty array or an array that contains the removed elements (if any).
Example: remove element from array in JavaScript
In this example, we want to remove 2 elements from the array starting at the position 1:
const arr = [1,2,3,4,5,6,7,8,9,10]; arr.splice(1,2); console.log(arr);
Output:
[1, 4, 5, 6, 7, 8, 9, 10]
Here, the value 2 and 3 are removed.
Example: JavaScript remove item from array
In this example, we want to add 4 new elements at the index number 3 and also remove 2 elements.
const arr = [1,2,3,4,5,6,7,8,9,10]; arr.splice(3,2,"Jack","John","Omid","Ellen"); console.log(arr);
Output:
[1, 2, 3, "Jack", "John", "Omid", "Ellen", 6, 7, 8, 9, 10]
Example: delete element from array
const arr = [1,2,3,4,5,6,7,8,9,10]; arr.splice(3,1,"Jack","John","Omid","Ellen"); console.log(arr);
Output:
[ 1, 2, 3, "Jack", "John", "Omid", "Ellen", 5, 6, 7,8,9,10]
Example: JavaScript insert into array
In this example, we want to add 3 new elements, starting at the position 2 without deleting any other elements.
const arr = [1,2,3,4,5,6,7,8,9,10]; arr.splice(2,0,"Jack","John","Omid"); console.log(arr);
Output:
[1, 2, "Jack", "John", "Omid", 3, 4, 5, 6, 7, 8, 9, 10]