Add and Remove Elements in an Array Using Splice

Laurie Barth
InstructorLaurie Barth

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Learn how to use splice with one, two or three+ arguments. With one argument splice removes all elements past that index. With two arguments it removes the number of elements specified past the first argument index. With three+ arguments it removes the elements specified and adds all elements passed into the function.

Instructor: [00:00] Define an array. We'll remove elements from that array using Splice. We'll begin with using only the first argument, which is the index where removal should begin.

[00:14] As we can see, since we used index four, only the last element is removed. We'll use Splice with two arguments, the second being the number of elements past that index that should be removed.

[00:33] We'll use Splice with the first two arguments as zero, and all remaining arguments as elements to add to the array. Since we're removing nothing, only add will be empty, and array will have our new elements.

[00:50] We'll add and remove elements at the same time. We'll begin our removal at index two and remove three elements. Our additions will also begin at index two.

[01:05] As we can see, we have the elements in the middle of our array that were removed and our new elements with four at the end of the array, because they were inserted in the middle.