What it is for

In JavaScript, arrays are a convenient way to keep data united by an argument in an  organized manner. In most cases, arrays are filled sequentially, starting from the first cell with a zero index. But during code execution we may need to add new data to the array cells that are already occupied, without deleting the existing ones. 

The most obvious way is to create a new array, then add new data and synchronize different versions of the array. But this is complicated and non-optimized. It's better to use the built-in Array method called splice(), which does the same thing just in one line of code.

The splice() method allows you to add one or more elements sequentially to an existing array. It is most efficient to add data to the beginning or middle part of an array. After adding new data, the method will re-index the elements, automatically increasing (or decreasing) the length of the array to the required value and removing empty cells (if they appear). 

It is also important to note that during execution of this method, changes will be applied directly to the original array, so check the syntax of parameters carefully.

Syntax

Array.splice() must be specified in relation to an array whose contents will be changed. Parameters that affect the execution of this command will be in brackets. 

There are two parameters here that determine the script for inserting new values and the ability to specify data for insertion. Accordingly, it performs insertion of values sequentially, starting from the specified cell.

The first (and always required) parameter is startIndex it's defining the index of the array element from which new values will be added. It must be a positive number (or equal to 0), but this method can handle other values as well. 

If this parameter is set as a negative number, it will start counting from the end of the array. At the same time, if the number is greater than the length of the array, it will add new values to the end of the array, automatically increasing its length.

Also, the delCount parameter can be added to the method. It is a figure which defines how many cells must be deleted after startIndex. This is an optional method, and if you don't want to delete the existing values of the array, its value must be zero or negative. In any case, the syntax of Array.splice() should look like this:

arrayName.splice(startIndex, delCount);

In addition, in brackets, you can specify the values that will be inserted into the array. The number of values for insertion is unlimited, but it affects the speed of the operation as a whole.This is an optional parameter, but if delCount is zero, at least one value must be specified to insert. If the method does not specify data for insertion, and delCount is greater than zero, then only deletion of values from the array will be performed.

arrayName.splice(startIndex, delCount, newRecord1, newRecord2…);

Note that regardless of specified parameters, Array.splice() will glue parts of the array and there wouldn't be empty cells in it. But this doesn't apply to situations when empty values are outside the range for insertion or are specified as parameters by the developer.

How to use Array.splice()

Thanks to the parameters, Array.splice() is very flexible in use. It can be used to perform data inserts into arrays under different conditions:

1. Inserting data

To insert data without deleting existing data, the second parameter (delCount) must be zero. For example, let's insert the word "banana" into the array instead of the fourth element:

let tropicFruits = [
  "orange",
  "papaya",
  "lemon",
  "maracuya",
  "pineapple",
  "mango",
];

tropicFruits.splice(4, 0, "banana");

console.log(tropicFruits); // Output: ['orange', 'papaya', 'lemon', 'maracuya', 'banana', 'pineapple', 'mango']

2. Replacing data

To replace existing data, the second parameter must be equal to the number of values which we want to add. Let's replace "orange" with "banana":

let tropicFruits = ['orange', 'papaya', 'lemon', 'maracuya', 'pineapple', 'mango'];

tropicFruits.splice(0, 1, 'banana');

console.log(tropicFruits); // Output: ['banana', 'papaya', 'lemon', 'maracuya', 'pineapple', 'mango']

Or let's replace the first two values in the array:

let tropicFruits = ['orange', 'papaya', 'lemon', 'maracuya', 'pineapple', 'mango'];

tropicFruits.splice(0, 2, 'banana', 'grapefruit');

console.log(tropicFruits); // Output: [ 'banana', 'grapefruit', 'lemon', 'maracuya', 'pineapple', 'mango' ]

3. Deleting existing data

Let's remove elements from the array, starting from the first to the third, and including third:

let tropicFruits = ['orange', 'papaya', 'lemon', 'maracuya', 'pineapple', 'mango'];

tropicFruits.splice(0, 3); 

console.log(tropicFruits); // Output: [ 'maracuya', 'pineapple', 'mango' ]

Test yourself

  • Task 1. Replace the names of the countries in the array with the names of their capitals using the Array.splice() method.

To do this, we need to set the parameters for the Array.splice() method. The first parameter will be "0" because we will start inserting from the first element of the array. The second parameter will be "5", in accordance with the number of array elements (length). And after that we will show the capitals of the countries via console.log(), separated by commas, in the order corresponding to the initial array.

let countryArr = ['Morocco', 'Greece', 'Poland', 'Canada', 'India'];

countryArr.splice(0, 5, 'Rabat', 'Athenes', 'Warsaw', 'Ottawa', 'New Delhi');

console.log(countryArr); // Output: [ 'Rabat', 'Athenes', 'Warsaw', 'Ottawa', 'New Delhi' ]
  • Task 2. Use Array.splice() to remove all even values, from the given array of numbers.

let numbersArr = [20, 69, 71, 42, 16, 75, 35, 87, 69, 22, 76, 8];

In the array, the even values are concentrated in three groups in different parts of the array. Therefore, we will remove them step by step, initializing the Array.splice() method separately for each group. It is necessary to take into account that the indices of the array values will be changed after every step with method execution.

let numbersArr = [20, 69, 71, 42, 16, 75, 35, 87, 69, 22, 76, 8];

numbersArr.splice(0, 1);

numbersArr.splice(2, 2);

numbersArr.splice(6, 3);

console.log(numbersArr); // Output: [ 69, 71, 75, 35, 87, 69 ]
  • Task 3. In the quote array, each element must match with word order from Neil Armstrong's quote, but there are errors. Using only the Array.splice() method, fix errors to match with the original: "That's one small step for a man, a giant leap for mankind."

let quoteArr = [
  'Initial',
  'array',
  'for',
  'map',
  'for',
  'a',
  'man',
  'a',
  'giant',
  'leap',
  'for',
  'mankind',
  'I',
  'think',
  'so',
];

To fix the quote, we use Array.splice() to make the following changes to the array one by one: 

  1. Replace "Another" with "That's"; 

  2. Add the word "one" after it; 

  3. Replace "road map" with "small step"; 

  4. Delete at the end of the array "in my opinion";

Print the corrected array to the console to check the result.

let quoteArr = [
  'Initial',
  'array',
  'for',
  'map',
  'for',
  'a',
  'man',
  'a',
  'giant',
  'leap',
  'for',
  'mankind',
  'I',
  'think',
  'so',
];

quoteArr.splice(0, 1, "That's");

quoteArr.splice(1, 0, 'one');

quoteArr.splice(2, 3, 'small', 'step');

quoteArr.splice(12, 3);

console.log(quoteArr); // [ 'That's', 'one', 'small', 'step', 'for', 'a', 'man', 'a', 'giant', 'leap', 'for', 'mankind.' ]

FAQ

What's the difference between slice() and splice()?

Slice(), after execution, returns a new array in accordance with the specified condition. Also, using this method, you cannot make changes to either the original or the received array.

What's the difference between delete() and splice()?

Delete() removes the contents of the cell, doesn't return any values, and doesn't re-index the array elements after execution.

What's the difference between push() and splice()?

Push adds new elements, but only to the end of the array, and returns its length after execution.