Add and Remove Elements in an Array Using Splice

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years 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.

egghead
egghead
~ 17 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today