Some Powerful Things You Can do With the Array Splice Method in JavaScript
By: Lincoln W Daniel
Tags: Coding, Programming, Data Structures, JavaScript, Arrays

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

Photo by Nicole Wolf on Unsplash

Remove element(s) from an array

This may seem like a problem with a trivial solution, but it’s not as easy as you might think at first thought. You might think to use delete array[index] , but while that would indeed unset the value at the index in the array, the array will end up with an empty index with an undefined value. This isn’t the goal. Then, you might think to shift the array’s element using array.shift() , but that only works if the target element is at the first index in the array; also, shift only removes one element at a time, what if you want to remove multiple elements at once? This is where splice comes in handy:

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

Splicing an array has a primary function of removing elements from an array, but it can do so much more. In this section, we will take a look at how we can use the splice method to insert multiple elements at a specific index in our array without removing any existing elements:

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:

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

In many interactive programs, a user may want to move items around in a list. The programmer, knowing of this use case ahead of time, may choose to store the items in an array so that they can display its contents to the user in a list. With the items in a list, the user can push a button to move an item up or down in the list.

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

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:

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

If you want to remove all elements from your array, you can do that by setting the length of your array to 0. If you want to remove the tail of your array, you can also do that by setting the array’s length to a value that is less than its current length; array.length = array.length — 2 would remove the last two elements. However, if you want to remove elements in the middle of your array, that requires a bit more thinking if you don’t know how to leverage the splice method. Splicing your array to remove elements from the middle of your array is easy; here’s how:

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

One other thing you can do via splicing is swap two elements, but I decided not to cover that here because there are simpler ways to achieve the same. In case you’re curious, here’s how that might look:

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