Some Powerful Things You Can do With the Array Splice Method in JavaScript

Lincoln W Daniel
May 24, 2020 · 6 min read

The splice method of the Array prototype in JavaScript is quite powerful when it comes to adjusting the contents of an array in place. You can use it to remove elements, add elements, reposition elements, and even swap elements. According to Mozilla, this is the function of Array.prototype.splice():

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. — MDN Web Docs

Image for post
Image for post
Photo by Nicole Wolf on Unsplash

Remove element(s) from an array

Image for post
Image for post

In that code, our array starts as [“one", “two", “three", “four"]. We use splice to remove two (2) of its elements starting at index 1. The removed elements, the result of the splice call, are stored in removedElements as ["two", "three"]. After this operation, our array has been readjusted to only contain the other two elements, so it looks like this: ["one", "four"].

Insert elements at an index in an array

Image for post
Image for post

In this code, we were able to easily add three new elements to our array starting, arbitrarily, at index 1. We could add one or an unlimited number of elements to our array at any index using the splice method. Let’s see how we could use this method to merge two arrays with the help of the ES6 spread operator:

Image for post
Image for post

In this example, we were able to use the spread operator () as the final argument to list.splice in order to merge the contents of secondList into our original array, list. This is handy when you want to merge an array of an unknown length into another array at any desired index without having to engage complicated looping logic.

Move an element to a new index

There are many complicated ways to accomplish this goal, but the splice method makes it quite trivial:

Image for post
Image for post

In that code, we target the last item in the list, “three”, which is at index 2 (currentIndex). We want to move it up one position in the list, so we want its new index to be 1. This operation would move it from the last position to the second position in the list.

We are able to achieve the goal in two simple steps using two calls to splice on the array. The first step is to remove the target element from the array at its current index; we do this by calling list.splice(currentIndex, 1) . In the same step, we store the first and only element in the resultant array of that splice call in a variable targetElement because we’ll need it in the next step.

The second and final step is to put the target element back in the array at its new index. We call on splice once more to do just that: list.splice(newIndex, 0, targetElement). This final call will delete zero (0) items from the array starting at the new index, then add the target element starting from that same index. In other words, this call to splice simply puts the target element at the desired index without affecting any other elements in the array. Easy.

In the end, we successfully change our array from ['one', 'two', 'three'] to ['one', 'three', 'two'] . We could have done this in a single line, but I chose to expand the code in the interest of readability.

For fans of functional programming, here it is as a pure function with help from the ES6 spread operator:

Image for post
Image for post

The other methods of doing this repositioning of an element are quite involved and require more steps than what we’ve done here.

Note that this is not the same as a swap method. I touch on this later.

Remove all elements between two indices exclusive

Image for post
Image for post

We’re able to remove an arbitrary number of elements between two indices (exclusively) using the array’s splice method. With the help of some math, we are able to provide the indices in any order — (startIndex, endIndex) or (endIndex, startIndex). This operation will remove all of the elements between the two indices in the array without affecting the elements at the respective indices.

Honorable mention

function swapElements(list, index1, index2) {
list.splice(
Math.min(index1, index2), 0,
list.splice(Math.max(index1, index2), 1)[0]
)
list.splice(
Math.max(index1, index2) , 0,
list.splice(Math.min(index1, index2) + 1, 1)[0]
)
}
const list = [ 'one', 'two', 'three', 'four', 'five' ]
swapElements(list, 1, 3)
console.log(list)
// [ 'one', 'four', 'three', 'two', 'five' ]

Try this code for yourself and see if you can reason about what’s going on in those four calls to the splice method. Again, there are simpler ways to do a swap in JavaScript, but this is another in case, for some reason, splice is all you’re allowed to use.

Conclusion

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

Creating more winners in writing @Penname.me | Author @JavaForHumans | Created Smedian.com | Ex: Founder & Editor in Chief @MarkGrowth (acq.)

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

Creating more winners in writing @Penname.me | Author @JavaForHumans | Created Smedian.com | Ex: Founder & Editor in Chief @MarkGrowth (acq.)

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store