The Wayback Machine - https://web.archive.org/web/20241004114958/https://www.geeksforgeeks.org/javascript-array-splice-method/
Open In App

JavaScript Array splice() Method

Last Updated : 05 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to change the contents of an array by removing or replacing existing elements and/or adding new elements. It modifies the original array and returns an array of the removed elements.

Syntax

Array.splice( index, remove_count, item_list )

Parameters:

  • index: It is a required parameter. This parameter is the index from which the modification of the array starts (with the origin at 0). This can be negative also, which begins after many elements counting from the end.
  • remove_count: The number of elements to be removed from the starting index.
  • items_list: The list of new items separated by a comma operator that is to be inserted from the starting index.

Return Value:

While it mutates the original array in place, still it returns the list of removed items. In case there is no removed array it returns an empty array.

Example 1: Basic Usage of splice() Method

In this example, JS is replaced with “PHP” and React_Native, and React is inserted at the second-to-last index.

JavaScript
let webDvlop = ["HTML", "CSS", "JS", "Bootstrap"];

console.log(webDvlop);

// Add 'React_Native' and 'Php' after removing 'JS'.
let removed = webDvlop.splice(2, 1, 'PHP', 'React_Native')

console.log(webDvlop);
console.log(removed);

// No Removing only Insertion from 2nd 
// index from the ending
webDvlop.splice(-2, 0, 'React')
console.log(webDvlop)

Output
[ 'HTML', 'CSS', 'JS', 'Bootstrap' ]
[ 'HTML', 'CSS', 'PHP', 'React_Native', 'Bootstrap' ]
[ 'JS' ]
[ 'HTML', 'CSS', 'PHP', 'React', 'React_Native', 'Bootstrap' ]

Example 2: Manipulating an Array with splice() Method

In this example we demonstrates modifying the languages array. It first replaces ‘Html’ with ‘Julia’ and ‘Php,’ then inserts ‘Pascal’ before the second-to-last element, logging the changes throughout.

JavaScript
let languages = ['C++', 'Java', 'Html', 'Python', 'C'];

console.log(languages);

// Replace 'Html' with 'Julia' and 'Php'.
let removed = languages.splice(2, 1, 'Julia', 'Php');

console.log(languages);
console.log(removed);

// Insert 'Pascal' before the second-to-last element.
languages.splice(-2, 0, 'Pascal');
console.log(languages);

Output
[ 'C++', 'Java', 'Html', 'Python', 'C' ]
[ 'C++', 'Java', 'Julia', 'Php', 'Python', 'C' ]
[ 'Html' ]
[
  'C++',    'Java',
  'Julia',  'Php',
  'Pascal', 'Python',
  'C'
]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

JavaScript Array splice() Method- FAQs

How do you use the splice() method?

The splice() method is used with the following syntax:

array.splice(start, deleteCount, item1, item2, …);

Can you use splice() to only add elements to an array without removing any?

Yes, by omitting the items to add, you can remove elements without adding any.

What happens if the start index is negative?

If the start index is greater than the array length, splice() will start adding the new elements at the end of the array without removing any elements.

What if the deleteCount parameter is not specified?

If the deleteCount parameter is not specified, all elements from the start index to the end of the array are removed.

Can splice() be used on non-array objects?

While splice() is a method of array objects, it can be called on array-like objects using Function.prototype.call() or Function.prototype.apply().


Previous Article
Next Article

Similar Reads

Alternative of Array splice() method in JavaScript
The array splice() method is a method of JavaScript and In this article, we are discussing what are alternatives to this method. Here are 2 examples discussed below. Approach 1: In this approach, the startIndex(From where to start removing the elements) and count(Number of elements to remove) are the variables. If the count is not passed then treat
3 min read
What is the difference between Array.slice() and Array.splice() in JavaScript ?
In JavaScript, slice() and splice() are array methods with distinct purposes. `slice()` creates a new array containing selected elements from the original, while `splice()` modifies the original array by adding, removing, or replacing elements. slice():The slice() method in JavaScript extracts a section of an array and returns a new array containin
3 min read
Delete the array elements in JavaScript | delete vs splice
This article will show you how to Delete the array element at a specific position using JavaScript. There are two approaches that can be used to delete elements in an array. They have their own merits regarding the way they perform the deletion. Delete array[index]:This method deletes the element at the index specified but does not modify the array
3 min read
How to Splice Duplicate Item from JavaScript Array?
Given an array of numbers or strings containing some duplicate values, the task is to remove these duplicate values from the array without creating a new array or storing the duplicate values anywhere else. Examples: Input: arr = [1, 2, 3, 4, 3, 2, 1];Output: [1,2,3,4]Input: [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5];Output: [4, 1, 5, 2, 6, 8, 7]Table of
4 min read
TypeScript Array splice() Method
The Array.splice() is an inbuilt TypeScript function that changes the content of an array by adding new elements while removing old ones. It takes an index, a count of elements to remove, and optional elements to add, returning the removed elements and modifying the original array. Syntaxarray.splice(index, howMany, [element1][, ..., elementN]); Pa
3 min read
How to splice an array without mutating the original Array?
In this article, we will be extracting the range of elements from an array without mutating it. Here, mutation means the changing of the original array. There is a built-in function that is made for the extraction of elements from the array but it mutates the array. How does the splice() method work? The splice method is used to extract the range o
4 min read
What is Splice in JavaScript ?
In JavaScript, splice() is a method that can be used to change the contents of an array by removing or replacing existing elements and/or adding new elements. It is a versatile method that allows you to modify arrays in-place. Syntax:array.splice(startIndex, deleteCount, item1, item2, ...);Parameters:startIndex: The index at which to start changing
1 min read
Collect.js splice() Method
The splice() method is used to remove and returns a slice of items starting at the specified index Syntax: collect(array).splice() Parameters: The collect() method takes one argument that is converted into the collection and then splice() method is applied on it. Return Value: This method returns a slice of items starting at the specified index. Be
1 min read
How to use splice on Nested Array of Objects ?
Using the splice() method on a nested array of objects in JavaScript allows you to modify the structure of the nested array by adding or removing elements at specified positions. Table of Content Accessing the nested array directlyUtilizing a combination of array methodsAccessing the nested array directlyThis approach directly accesses the nested a
2 min read
How to Update an Array After Splice in Svelte?
When you use splice() to modify an array in Svelte, such as adding or removing items, simply calling the method won't trigger a UI update because Svelte relies on reactivity, which requires the array to be reassigned. This article explores two ways to ensure the array updates correctly after a splice() operation and how these changes are reflected
4 min read
p5.js splice() function
The splice() function in p5.js is used to insert values or array elements in the given array.Syntax: splice(Array, Values, Position) Parameters: This function accepts three parameters as mentioned above and described below: Array: This is a given array which is to be modified.Values: This is the values or an another array whose elements are to be i
3 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How does Promise.all() method differs from Promise.allSettled() method in JavaScript ?
In this article, we will first understand in brief the Promise.all() as well as Promise.allSettled() methods and then we will try to visualize how they differ from each other through some theoretical as well as some coding examples. Both Promise.all() and Promise.allSettled() methods are the methods of a Promise object (which is further a JavaScrip
4 min read
How does Promise.any() method differs from Promise.race() method in JavaScript ?
In this article, we will first try to understand how we may declare or use Promise.any() and Promise.race() methods followed by some facts which will eventually help us to understand how they differ from each other (through theoretical as well as coding examples). Let us first quickly understand in brief about both the methods followed by their syn
5 min read
How toReversed() method is different from reverse() method in JavaScript
In JavaScript, reverse() and toReversed() methods do the same job as reversing but toReversed() does not change the original array. The reverse() method changes the original array. Below we have explained both methods. Table of Content Reverse() MethodtoReversed() methodReverse() MethodThe reverse() method is a built-in method for arrays in JavaScr
2 min read
Implement polyfill for Array.prototype.map() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.map() method in JavaScript. What is a polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the br
3 min read
JavaScript Array map() Method
JavaScript Array map() Method method creates a new array with the results of a called function for every array element. This function calls the argument function once for each element of the given array in order. Syntax: // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /*
3 min read
JavaScript Array valueOf() Method
The JavaScript Array valueOf() method in JavaScript is used to return the array. It is a default method of the Array Object. This method returns all the items in the same array. It will not change the original content of the array. It does not contain any parameter values. Syntax: array.valueOf()Parameters: This method does not accept any parameter
2 min read
How to use Array.prototype.reduce() method in JavaScript ?
The Array.prototype.reduce() method is used in an array to return a single value from an array after executing the user-supplied callback function on each element of the array. It transverses from the left-most-element to the right-most-element of the given array. Array.prototype.reduce() can be called using two ways. Callback function: The functio
3 min read
Which one method use to delete an element from JavaScript array (slice or delete) ?
We can use both methods to delete an element from a javascript array. The answer is solely dependent on the application and on the programmer. What slice() method does? The slice method, as the name suggests, slices an array and returns a copy of the new array. This method does not affect the main array, it just returns the copy of the array. We ca
4 min read
Which built-in method removes the last element from an array and returns that element in JavaScript ?
In this article, we will know how to remove the last element from an array using the built-in method in Javascript, along with understanding its implementation through the examples. There are a few Javascript built-in methods and techniques with which we can remove the last element of the array. We will focus only on the 2 methods ie., the pop() me
3 min read
Implement polyfill for Array.prototype.reduce() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.reduce() method in JavaScript. A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or the new version of the browser does not have that
2 min read
JavaScript Array findLastIndex() Method
The Javascript findLastIndex() method is used to find the index of the last element in an array that matches the specified condition. It works by iterating over the array from the end to the beginning and returning the index of the first element that satisfies the condition specified in a callback function. If no element matches the condition, the
2 min read
How the Array.unshift() method works in JavaScript ?
The Array.unshift() method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array after the elements have been added. Key points about Array.unshift(): It modifies the original array and returns the new length.It can accept multiple arguments, and each a
1 min read
What is the use of the Array.from() method in JavaScript ?
In JavaScript, the Array.from() method is used to create a new array instance from an iterable object or array-like object. It provides a way to convert objects that are not inherently arrays into actual arrays. Example: Here we see that output creates a new array whose content is the same as input in the case of an integer. C/C++ Code console.log(
1 min read
What is the use of the Array.some() method in JavaScript ?
The Array.some() method in JavaScript is used to check if at least one element in an array satisfies a given condition. It returns true if at least one element in the array passes the test implemented by the provided function otherwise, it returns false. Example: Here, the condition in the some() method checks if there is at least one element great
1 min read
What is the use of the Array.of() method in JavaScript ?
The JavaScript array.of() method is an inbuilt method in JavaScript that creates a new array instance with variables present as the argument of the method. Example: Here, Array.of() method is used to create new array instances with a variable number of arguments. C/C++ Code // Here the Array.of() method creates a new Array instance with // a variab
1 min read