The JavaScript splice() technique replaces or removes array elements while they are still in place.

Syntax

The syntax is as follows:

removedArray = array.splice(index, count, item1......itemN)

Removed Array : 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

Examples

The examples that demonstrate various applications of the splice() technique are shown below.

  • Eliminate all elements that come after the initial 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']
  • Change every element that comes after the initial 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']
  • At index 2, place 2 elements in place of 0 (zero) elements.
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 []
  • Delete all the elements after a particular 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']

Note - The original array is updated using the splice() technique, as opposed to the slice() method, which leaves the original array unchanged.


Recommended Posts

View All

Difference between var and let in JavaScript


Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...

What is prototype and prototype chaining in JavaScript


This article explains the concept of prototype and prototype chaining in JavaScript. Learn how prototypes work, how they are used to create inheritanc...

JavaScript Template Literals Explained


JavaScript template literals are one of JavaScript's most powerful capabilities. They enable us to generate dynamic strings without the need for conca...

What is memoization?


Memoization is a programming technique that improves efficiency by caching results of expensive function calls. Learn more about it here.

JavaScript Program to Create Objects in Different Ways


Learn different ways to create objects using JavaScript with our step-by-step guide. From object literals to constructor functions and classes, this p...