In this article, we will be taking a deep dive into Javascript arrays and how we can modify an array, i.e. add, remove, or replace elements using the splice() method.
What are Arrays in JavaScript?
Arrays are linear data structures used to store homogenous data, i.e. same type of data. An array can contain all integers, all characters, or all strings as the elements. An array can not be a combination of integers and characters, or integers or strings. Let us take a look at how to declare and use arrays in Javascript.
//declaring an integers array
let marks = [98, 75, 62, 82, 97, 53];
//declaring a characters array
let grades=['A', 'B', 'A', '0'];
//declaring a strings array
let favtutors=["John", "Joshua", "Alex", "Kate"];
//declaring a boolean array
let present=[true, false, false, true];
In the code above, we have made integers array marks containing all integers, a characters array grade consisting of all elements as characters, a strings array ‘favtutors’ consisting of all strings, and a boolean present array consisting of all boolean values.
In JavaScript, we do not need to specify the type of the array at the compile time as it is a dynamically typed language.
Array splice() function in JavaScript
Splice means to unite or combine two separate elements into a whole. If we want to push some more elements to an array or delete some elements already present in the array, we splice the array. So, we can perform splicing on an array if we want to remove, add, or replace elements.
To perform the splice operation, we have an inbuilt function. The array splice() method in JavaScript allows one to modify the contents of an array by removing, adding, or replacing elements. Note that the splice() method modifies the original array.
The general syntax of the array splice() method in JavaScript is:
array_name.splice( index, remove_count, items);
- array_name: Name of the array to be spliced
- index: The index from which the array must be changed/modified. It is a required parameter and can have positive, 0, or negative values.
- remove_count: Specifies the number or the count of the items to be removed from the array.
- items: Represents the list of items to be added to the array. It is an optional parameter. If no item is to be added, the parameter is simply not given in the function.
Note that, this is the general syntax of the splice function. It can be implemented in various ways which we will understand in the further sections.
The splice() method is a standard feature of the ECMAScript JavaScript and is supported by all modern browsers, including Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge. It is also supported in older versions of Internet Explorer.
Use of splice() Method
Let’s now learn what are the use cases of the splice() method. In this section, We will take a look at how to remove elements from various positions in an array in JavaScript using the splice() function. We can remove elements both from the start and end of an array in JavaScript.
Removing Elements from the Start of an Array
We will first understand how to remove elements from the beginning of an array. Let’s take several examples.
Example 1:
- Define the marks array as marks=[98, 78, 92, 83, 65]
- Say, we have to remove three elements from the marks array from index 2. Note that in the array, indices always start from 0. So the element present at index 2 = 92.
- Taking parameters into consideration, here the index = 2 (index starting where we want to remove elements). As we want to remove 3 elements, count = 3.
Check out the code below.
//declaring a marks array let marks=[98, 78, 92, 83, 65] //we want to remove the marks of 3 students after index 2, i.e. after 92 marks.splice(2,3); //printing the modified marks array console.log(marks);
Output:
[ 98, 78 ]
So, clearly, 3 elements starting from index 2 (i.e 92) are removed from the array marks.
Example 2:
Let us take another example.
- Now we want to remove two elements starting from index 2. We observe that the number of elements after the 2nd index (including it) is three (92, 83 & 65).
- But we are only removing 2 elements after the second index. So the last element i.e. 65 is not removed and will still be in the marks array.
//declaring a marks array let marks=[98, 78, 92, 83, 65] //we want to remove marks of 2 students(till the end) after the index 2, i.e. after 92 marks.splice(2,2); //printing the modified marks array console.log(marks);
Output:
[ 98, 78, 65 ]
To print the elements removed, simply make an array and store the deleted elements in the array deletedMarks.
//declaring a marks array let marks=[98, 78, 92, 83, 65] //we want to remove marks of 2 students(till the end) after the index 2, i.e. after 92 let deletedMarks=marks.splice(2,2); //printing the modified marks array console.log(marks); //printing the deleted marks console.log(deletedMarks);
Output:
[ 98, 78, 65 ]
[ 92, 83 ]
Removing Elements from the End of an Array
The negative value is used as the index parameter to remove the element from the end of an array. Let’s have a look at some examples.
Example 3:
- We will remove one element from the names array from the last (the first element from the last) and hence index parameter is provided as -1.
- We have to remove just one element from the names array, so the count is given as 1.
Code:
//declaring a names array let names=["John", "Joshua", "Alex", "Katie"] //we want to remove the 1 name from the end i.e. Katie names.splice(-1, 1); //printing the modified names array console.log(names);
Output:
[ ‘John’, ‘Joshua’, ‘Alex’ ]
Example 4:
- We will remove two elements from the names array from the second last and hence index parameter is provided as -2.
- We have to remove two elements from the names array, so the count is given as 2.
Look at the code given below.
//declaring a names array let names = ["John", "Joshua", "Alex", "Katie"] //we want to remove the 2 names from the second last index i.e. Katie let deletedNames = names.splice(-2, 2); //printing the modified names array console.log(names); //printing the deleted names console.log(deletedNames);
Output:
[ ‘John’, ‘Joshua’ ]
[ ‘Alex’, ‘Katie’ ]
We have obtained the desired output.
Removing the Elements along with Adding Some Elements
Let’s say, we want to remove elements from an array along with adding some other elements. We simply provide a list of elements to be added as the parameters after the count parameter. Let us take a look at the example below.
//declaring a marks array let marks=[98, 78, 92, 83, 65] //we want to remove marks of 3 students(till the end) after the index 2, i.e. after 92 //and we also want to add some elements to the array let deletedMarks=marks.splice(2,3,99,100); //printing the modified marks array console.log(marks); //printing the deleted marks console.log(deletedMarks);
Output:
[ 98, 78, 99, 100 ]
[ 92, 83, 65 ]
In this example, we have removed three elements after index 2 and added two other elements, i.e. 99 and 100 to the marks array. We have simply provided 99 & 100 as parameters after the count (=3) parameter in the array splice function.
In this section, we will take a look at how to add elements at various positions in an array in JavaScript using the splice() function.
Adding Elements at the End of an Array
To add elements at the end of an array using the splice() method, you need to provide the starting index as the length of the array and the number of elements to remove as 0.
Take a look at the below example.
//declaring a marks array let marks=[98, 78, 92, 83, 65] //adding elements at the end of an array without deleting any let deletedMarks=marks.splice(4,0,99,100); //printing the modified marks array console.log(marks); //printing the empty deleted marks array as no element is deleted console.log(deletedMarks);
Output:
[ 98, 78, 92, 83, 65, 99, 100 ]
[ ]
We have not removed a single element and hence the array “deletedMarks” is empty. We have instead added two elements 99 and 100 to the array by providing them as parameters to the splice() function.
Adding Elements at Specific Indexes
You can also use the splice() method to add elements at specific indexes in an array. Simply provide the desired starting index and the number of elements to remove as 0. Here’s an example:
//declaring a marks array let marks=[98, 78, 92, 83, 65] //adding elements at the index 2 of an array without deleting any let deletedMarks=marks.splice(2,0,99,100); //printing the modified marks array console.log(marks);
Output:
[ 98, 78, 99, 100, 92, 83, 65 ]
We have used the index=2, therefore elements 99 and 100 are added at index two and the rest of the elements are shifted to the right with none being deleted.
Replacing Elements with the splice() Method
If we think logically, Replacing just means deleting the elements at a particular index and adding some other elements at their place (the same index). So, Replacement of the elements is the combination of removal and addition of elements to the array.
//declaring a marks array let marks=[98, 78, 92, 83, 65] //replacing 2 elements from the index 0 let deletedMarks=marks.splice(0,2,99,100); //printing the modified marks array console.log(marks);
Output:
[ 99, 100, 92, 83, 65 ]
In the above example, we first provide the index parameter as 0 starting with which two elements will be deleted (as the count=2). Then, we have provided a list of elements to be added to the array. Hence, we obtain the desired output.
Important Points to Keep in Mind
First, when working with empty arrays, the behavior of the splice() method differs slightly. If you call splice() with no arguments, it won’t remove any elements from the array.
//declaring empty marks array let marks = []; //splicing the empty array let deletedMarks = marks.splice(); //printing both arrays console.log(marks); console.log(deletedMarks);
Output:
[ ]
[ ]
In this example, we call splice() on an empty array. The method doesn’t remove any elements and returns an empty array.
Also, if you provide an invalid index to the splice() method, splice() will attempt to perform the operation. If the index greater than the length of the array is provided, it will behave as an adding function and add the new elements to the array.
//declaring nums array let nums = [1, 2, 3]; //providing index greater than the length of the array and trying to store deleted elements let del = nums.splice(5, 0, 4, 5); //printing both arrays console.log(nums); console.log(del);
Output:
[ 1, 2, 3, 4, 5 ]
[ ]
In this example, we provide an index (5) greater than the length of the numbers array. The splice() method adds the new elements (4 and 5) to the array.
Finally, remember that the splice() method modifies the original array. If you want to avoid mutating the original array, you can make a copy of it before performing the splice operation. This can be done using the spread operator or the slice() method.
You can now move on to learn about the filter() method in JavaScript here.
Conclusion
In this blog, we discussed the built-in splice() function and its various types of approaches to add, remove, and replace elements out of an array. It is very important to keep the important points in mind to use this method effectively.