5) Arrays, Objects and Useful Tools Lesson

How to Insert, Delete or Replace Array Items: JavaScript's .splice()

13 min to complete · By Ian Currie

One of the most common JavaScript array operations is to add and remove elements from them. In this lesson, you'll focus in on the particularly versatile .splice() method that can be tailored to suit many situations involving array manipulation. This approach provides a flexible solution to handle a wide range of tasks associated with arrays.

The .splice() method offers flexibility in array manipulation, accommodating various arguments including optional ones, which will allow you to practice essential skills for efficient JavaScript programming.

How to Use .splice()

The splice() method in JavaScript is a versatile tool for modifying arrays, allowing you to add and delete items at specific index points.

The parameters for the .splice() array method are:

  • Required parameter: Index to start the operation
  • Required parameter: How many items to delete from the array (can be zero)
  • Optional parameters: Items to add at the index location after deletion

As you can see, it looks like this method will allow you to delete items, it allows you to add items, and it also allows you to do both operations in one method call. Take a sneak peek at what it looks like in action:

let colors = ["red", "blue", "green", "orange"];
colors.splice(1, 2, "yellow", "cyan", "magenta");
console.log(colors); // ["red", "yellow", "cyan", "magenta", "orange"]

In this example, two items were removed from the array and three were inserted where the two items were previously.

In the following sections, you'll break down the operations of the JavaScript .splice() methods into it's component parts.

Adding Items to an Array with .splice()

You can use the JavaScript array .splice() method to add an item to a certain index position.

If wanted to add an item to the second index of an array, which would be index 1 you could do the following:

let colors = ["red", "blue", "green", "orange"];
colors.splice(1, 0, "purple");
console.log(colors); // ["red", "purple", "blue", "green", "orange"]

In this example, .splice() is called at index 1, told to remove 0 items, and add in "purple" at index 1. The end result is an array with an extra item.

Colorful illustration of a light bulb

The splice() method in JavaScript mutates, or changes, an array in place. When you head that a method does something "in place" it means that the method alters the original array directly, rather than creating a new array with the changes.

When you use splice(), the original array is updated to reflect any additions, deletions, or replacements you've made. This contrasts with methods that return a new array with the changes, like the sister method to .splice() which is .toSpliced():

let colors = ["red", "blue", "green", "orange"];
colors.toSpliced(1, 0, "purple");
console.log(colors); // ["red", "blue", "green", "orange"] No change!
colors = colors.toSpliced(1, 0, "purple"); // Need to assign the result
console.log(colors); // ["red", "purple", "blue", "green", "orange"]

The .toSpliced() method is identical to .splice() in terms of it's parameters, where it differs is in the way it creates a new array and returns that result.

With splice(), there's no need to assign the result to a new array to see the changes; they're applied directly to the array you're working on. The changes are applied in place.

You can also add more arguments to the end of the method call to add more than one item:

let colors = ["red", "blue", "green", "orange"];
colors.splice(1, 0, "purple", "black");
console.log(colors); // ["red", "purple", "black", "blue", "green", "orange"]

You can add as many extra items to add to the array as you'd like!

Now that you've seen how .splice() can be used to add an item to an array, now you'll move on to see how it can be used to delete an item.

Delete an Item from a JavaScript Array using .splice()

Now to delete an item from a JavaScript array with .splice(). Take a look at this example:

let colors = ["red", "blue", "green", "orange"];
colors.splice(2, 1);
console.log(colors); // ["red", "blue", "orange"]

Splice is called at index 2, told to remove 1 item, and since the following argument is omitted, it does not insert any items. All it does is delete "green" from the array.

Delete and Add Items at the Same Time With JavaScript Array .splice()

The true power of .splice() lies in its ability to perform deletion and addition simultaneously. This makes it incredibly useful for replacing items in an array:

let colors = ["red", "blue", "green", "orange"];
colors.splice(1, 2, "turquoise", "violet");
console.log(colors); // ["red", "turquoise", "violet", "orange"]

In this case, .splice() starts at index 1, removes two items ('blue', 'green'), and then adds 'turquoise' and 'violet' at the same index.

Here's a more complex scenario where you need to iterate through a large array to replace specific items where .splice() could come in very handy:

let largeArray = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew"];

// Suppose you want to replace every fruit that starts with a vowel with "kiwi"
for (let i = 0; i < largeArray.length; i++) {
  if ('aeiou'.includes(largeArray[i][0].toLowerCase())) {
    largeArray.splice(i, 1, "kiwi");
  }
}

console.log(largeArray); // ['kiwi', 'banana', 'cherry', 'date', 'kiwi', 'fig', 'grape', 'honeydew']

In this example, the for loop iterates through the array. Whenever it encounters a fruit whose name starts with a vowel, it uses .splice() to replace that fruit with "kiwi" at the same index.

Here's a breakdown of the operations that happen on each iteration:

  • if ('aeiou'.includes(largeArray[i][0].toLowerCase())) { ... }: This is an if statement that checks a condition.
    • 'aeiou': You write a string containing all the vowels.
    • .includes(...): A neat string method that checks if a given string is present within another string.
    • largeArray[i][0]: Accesses the first character of the ith element in largeArray.
    • .toLowerCase(): Converts the character to lowercase. This ensures the comparison is case-insensitive.
  • If the first character of the current fruit (in lowercase) is a vowel (i.e., present in 'aeiou'), the code inside the if statement executes.
  • largeArray.splice(i, 1, "kiwi"): This line is executed if the condition is true.

In summary, for each element in largeArray, the code checks if it starts with a vowel. If it does, that element is replaced with "kiwi". Pretty nifty!

Negative Indexing When Using .splice(): a Neat Trick

JavaScript's .splice() also has a neat trick. .splice() allows negative indexing, where negative values count back from the end of the array:

let colors = ["red", "blue", "green", "orange"];
colors.splice(-2, 1, "pink");
console.log(colors); // ["red", "blue", "pink", "orange"]

Here, -2 refers to the second-to-last item in the array, allowing for intuitive array manipulation from the end.

Negative indexing as a feature that allows counting backwards from the end of an array, gained popularity through Python. In JavaScript, methods like .splice() and .slice() have adopted this approach. However, it's important to note that standard array and string indexing in JavaScript do not support negative indexing!

The nature of JavaScript includes some inconsistencies that can be challenging, such as its selective acceptance of negative indices in certain functions. However, encountering irregularities is a common aspect of programming, not just confined to JavaScript. As a programmer, it's important to recognize and adapt to these imperfections, whether in JavaScript or any other language. Embracing and understanding these quirks are essential skills for effective coding and problem-solving in the ever-evolving landscape of software development.

Summary: How to Add and Delete Array Items - JavaScript splice

  • .splice() is versatile, allowing addition, deletion, and replacement of array elements in a single operation.
  • The method's parameters include a start index, a count of items to remove, and optional items to add.
  • .splice() changes the array in place, directly altering the original array.
  • It allows for negative indexing, counting back from the end of the array for positional references.
  • This method exemplifies the object-like behavior of arrays in JavaScript, showcasing their flexibility and power.