Dynamic Array Manipulation with JavaScript's splice()

Hero image for Dynamic Array Manipulation with JavaScript's splice(). Image by Declan Sun.
Hero image for 'Dynamic Array Manipulation with JavaScript's splice().' Image by Declan Sun.

JavaScript's Array.prototype.splice() is a mutable method that changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. This method is a utility powerhouse, capable of performing multiple tasks at once – it can act as an inserter, remover, and even a replacer within an array's contents.

For this reason, it is also often misunderstood and misused, and sometimes even mistaken for slice(). So, today I'd like to quickly run through what it is, how it works, and what you need to be mindful of when using it on your data.


What is prototype.splice()?

splice() is an essential method in the Array prototype, which means it is a builtin property available on all array objects. It's a versatile tool that allows us developers to simultaneously perform element deletion, insertion, and replacement in a single, swift method call.


Syntax of prototype.splice()

The splice() method can take multiple arguments:

  • start: The index at which to start changing the array.
  • deleteCount (optional): An integer indicating the number of elements to remove from the array.
  • item1, item2, ... (optional): The elements to add to the array, starting at the start index.
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

How Does It Work?

When splice() is invoked, it modifies the original array in this order:

  1. Deletion:

    Starting from the start index, it removes deleteCount elements from the array.
  2. Insertion:

    It then inserts the new items (item1, item2, ...) into the array at the start index.
  3. Replacement:

    If items are added while elements are removed, it effectively replaces the removed elements with the new items.
  4. Returns:

    The method returns an array containing the deleted elements, if any, or an empty array if no elements are removed.

Some Examples in Code

Removing Elements

Here's a basic example splice() to remove elements:

const numbers = [1, 2, 3, 4, 5];const removed = numbers.splice(2, 1);console.log(numbers);  //=> [1, 2, 4, 5]console.log(removed);  //=> [3]

Here, we've used splice() to remove one element at index 2 (the number 3).

Adding Elements

splice() can also add elements without removing any:

numbers.splice(2, 0, 'three');console.log(numbers);  //=> [1, 2, 'three', 4, 5]

Now, we've added the string 'three' at index 2 without deletion by setting deleteCount to 0.

Replacing Elements

Replacing elements using splice() is as simple as removing and adding using the same call, like this:

numbers.splice(2, 1, 3);console.log(numbers);  //=> [1, 2, 3, 4, 5]

Here, we've replaced the string 'three' from the previous example with the number 3.


Caveats and Considerations

  • splice() is destructive – it changes the original array.
  • The start index can be negative, indicating the position from the end of the array.
  • If deleteCount is omitted, all elements from the start index to the end of the array will be removed.
  • The deleteCount can also be larger than the number of elements remaining in the array starting from the start index, in which case, all those elements will be removed.

In a Nutshell

Array.prototype.splice() stands out as a versatile and powerful tool in JavaScript for inplace array manipulation. It allows you to remove, add, and replace elements all within a single method. However, in true originalSpiderMan style: with great power comes the need for responsible usage.

Because splice() is mutable, it directly alters the original array, whereas some other array methods (like slice()) return a shallow copy of the original array. This can very quickly lead to unintentionally mutated, or corrupted data within your application if not done with caution.

Here are a few things I tend to remind junior developers when I see it coming up in their pull requests:

  • Always Remember the It's Destructive:

    Before using splice(), ensure that mutating the original array will not cause issues elsewhere in your code. If you need to preserve the original array, consider using methods like slice() to create a copy before manipulation.
  • Keep Track of Indexes:

    Since splice() modifies the array in place, the indexes of elements will shift as elements are added or removed. This can be particularly problematic if you are using loops or logic that relies on fixed index values. You have to be careful to adjust these based on the new mutated array.
  • Consider Readability:

    Whilst splice() can do many things at once, complex splice() operations can be difficult for others to read and understand. If your manipulation is getting complicated, it might be clearer to break it into separate operations or otherwise comment your code thoroughly.

Array.prototype.splice() offers immense utility in array manipulation within JavaScript. Whether you're looking to trim down arrays, inject new elements, or overhaul a section of an array, splice() stands as one of the goto methods for developers aiming for concise and efficient array operations.


Categories:

  1. Development
  2. Front‑End Development
  3. Guides
  4. JavaScript