How to use the splice() method in JavaScript

The JavaScript splice() method changes the elements of the array by replacing or removing the elements, in place.

Note: As compared to the slice() method which does not change the original array, splice() method changes are reflected in the original array.


Syntax

The syntax is as follows:

svg viewer
  • Removed: The array which stores all the removed elements that the splice() method returns
  • Array: The array on which splice() method is being applied
  • Splice: Function call to the method
  • Index: Starting index for the splice() method
  • Count: Specifies the number of items in the array to replace/remove from the starting index
  • Items: Items that replace the array elements from the starting index

Optional Arguments: Count and items arguments are optional in the function call.


Examples

Given below are some examples that show multiple ways to use the splice() method.


1. Remove all elements following the first element

var arr = ['A', 'B', 'C', 'D'];
var removed = arr.splice(1, arr.length-1);
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A']
// removed is ['B', 'C', 'D']

2. Replace all elements following the first element

var arr = ['A', 'B', 'C', 'D'];
var removed = arr.splice(1, arr.length-1, 'X', 'Y', 'Z');
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A', 'X', 'Y', 'Z']
// removed is ['B', 'C', 'D']

3. Remove 0 (zero) elements and insert 2 elements at index 2

var arr = ['A', 'B', 'C', 'D'];
var removed = arr.splice(2, 0, 'X', 'Y');
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A', 'B', 'X', 'Y', 'C', 'D']
// removed is []

4. Remove all elements following a specified index

var arr = ['A', 'B', 'C', 'D', 'E', 'F'];
index = 3
var removed = arr.splice(index);
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A', 'B', 'C']
// removed is ['D', 'E', 'F']
Copyright ©2024 Educative, Inc. All rights reserved