Splicing Arrays

Array Methods

Splicing Arrays

🙋 Need help? Ask an expert now!

The splice() method a combination of the methods that add and remove elements from an array. The splice() method can remove a number of elements and insert elements into an array. The syntax and the function of the splice() method is shown below.

arrayname.splice(index, count, elements)

  • Removes count elements, starting from index position
  • Adds elements at position index
  • Returns a new array, containing the removed elements

The different splice() methods above show how the splice() method can be used to achieve a wide range of actions in the array. The first splice() method removes 2 elements starting from index 0 and adds the elements "one" and "two" at index 0. This is why the end result is ["one", "two", 3, 4, 5]. The second splice() methods removes no elements from the array and adds "Jill", "Jim", and "Jacob" to the array at index 0. Therefore, the new array is [Jill, Jim, Jacob, John, Jack]. The last splice() method removes 2 elements from the array starting at index 0. This is why "Jill" and "Jim" are removed from the array.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 3, 4, 7, 11, 18];
arr.splice(0, 0, 0, 10);
arr.splice(0, 2);

What will the following code segment print to the console?