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...

Difference between Function, Method and Constructor calls in JavaScript


You are probably used to thinking about functions, methods, and class constructors as three distinct things if you are experienced with object-oriente...

Difference Between == and === in JavaScript


Learn the Difference Between == and === in JavaScript. Discover how each operator compares values and data types, and when to use them in code.

Useful websites every developer should know


There are numerous websites available nowadays to assist in the creation of a distinctive website.

What is currying function in JavaScript ?


Currying function in JavaScript allows you to transform a function that takes multiple arguments into a series of functions that each take one arg.