Applying JavaScript’s Splice Function


JavaScript is a lightweight programming language, and as with any programming language, when developing JavaScript programs, we often need to work with arrays to store data. In this article, we will introduce JavaScript’s built-in splice function and discuss how we can use it to manipulate an array. As data are generated, the structures used for storage must be updated. For this reason, a programmer must often add elements to or remove elements from an array.

The splice function is used to add elements to or remove elements from an array at a given index, and it returns the elements removed from the array. The syntax for the splice function is as follows:

 array.splice(index, removeCount, items...)

Here, index is the position at which we want to add or remove elements, removeCount, which is an optional argument, is the number of elements that we want to remove, and items, which is also optional, contains the elements we want to add.

Now, we will go over a few examples to show how the splice function is implemented.

First, suppose we have an array that consists of five elements.

 let arr = [10,20,30,40,50]

To remove the elements 20 and 30 (at position 1 and position 2 in the array, respectively) from the array, we simply call the splice function and tell it to start from the first index and remove 2 elements.

 arr.splice(1,2);


The values 20 and 30 are returned as the output. Next, we can look at the original array with the following command:

 console.log(arr);


The two elements returned in the output are no longer in the array.

Next, we will add elements to the array using the splice function. Because we will not remove elements from the array, we can provide a value of zero for removeCount and then provide the elements we want to add.

 arr.splice(2, 0, 30, 35);


The above command returns an empty array because no elements were removed. However, if we look at the original array, we can see that it has been updated.

 console.log(arr);

The values 30 and 35 were successfully added at the second index.

Finally, if we want to remove elements and add elements, we can provide values for both removeCount and items.

 arr.splice(1, 2, 15, 20, 25);

The above command has returned the two elements that were removed, and if we print the original array to the console, we can see that 20 and 30 are no longer in the array and that 15, 20 and 25 have been added.

 console.log(arr);

Conclusion

In this article, we discussed several ways to use the splice function to update arrays. We hope you found this article useful and continue to learn JavaScript with linuxhint.com.



from Linux Hint https://ift.tt/3juM65P

Post a Comment

0 Comments