- JavaScript Array splice: Delete, Insert, and Replace
- Deleting elements using JavaScript Array’s splice() method
- Inserting elements using JavaScript Array splice() method
- Replacing elements using JavaScript Array splice() method
- Javascript replace element in array
- # Table of Contents
- # Replace an Element in an Array in JavaScript
- # Replace an Element in an Array using Array.splice()
- # Replace an Element in an Array using a for loop
- # Replace an Element in an Array using Array.map()
- # Replace an Element in an Array using Array.forEach()
- # Additional Resources
- JavaScript: Update/Replace a Specific Element in an Array
- Using array[index] syntax
- Using the splice() method
JavaScript Array splice: Delete, Insert, and Replace
Summary: this tutorial shows you how to use the JavaScript Array’s splice() method to delete existing elements, insert new elements, and replace elements in an array.
JavaScript Array type provides a very powerful splice() method that allows you to insert new elements into the middle of an array. However, you can use this method to delete and replace existing elements as well.
Deleting elements using JavaScript Array’s splice() method
To delete elements in an array, you pass two arguments into the splice() method as follows:
Array.splice(position,num);
Code language: JavaScript (javascript)
The position specifies the position of the first item to delete and the num argument determines the number of elements to delete.
The splice() method changes the original array and returns an array that contains the deleted elements.
Let’s take a look at the following example.
Suppose, you have an array scores that contains five numbers from 1 to 5.
let scores = [1, 2, 3, 4, 5];
Code language: JavaScript (javascript)
The following statement deletes three elements of the scores array starting from the first element.
let deletedScores = scores.splice(0, 3);
Code language: JavaScript (javascript)
The scores array now contains two elements.
console.log(scores); // [4, 5]
Code language: JavaScript (javascript)
And the deletedScores array contains three elements.
console.log(deletedScores); // [1, 2, 3]
Code language: JavaScript (javascript)
The following figure illustrates the scores.splice(0,3) method call above.
Inserting elements using JavaScript Array splice() method
You can insert one or more elements into an array by passing three or more arguments to the splice() method with the second argument is zero.
Consider the following syntax.
Array.splice(position,0,new_element_1,new_element_2. );
Code language: JavaScript (javascript)
- The position specifies the starting position in the array that the new elements will be inserted.
- The second argument is zero (0) that instructs the splice() method to not delete any array elements.
- The third argument, fourth argument, and so on are the new elements that are inserted into the array.
Note that the splice() method actually changes the original array. Also, the splice() method does not remove any elements, therefore, it returns an empty array. For example:
Assuming that you have an array named colors with three strings.
let colors = ['red', 'green', 'blue'];
Code language: JavaScript (javascript)
The following statement inserts one element after the second element.
colors.splice(2, 0, 'purple');
Code language: JavaScript (javascript)
The colors array now has four elements with the new element inserted in the second position.
console.log(colors); // ["red", "green", "purple", "blue"]
Code language: JavaScript (javascript)
The following figure demonstrates the method call above.
You can insert more than one element by passing the fourth argument, the fifth argument, and so on to the splice() method as in the following example.
colors.splice(1, 0, 'yellow', 'pink'); console.log(colors); // ["red", "yellow", "pink", "green", "purple", "blue"]
Code language: JavaScript (javascript)
Replacing elements using JavaScript Array splice() method
The splice() method allows you to insert new elements into an array while deleting existing elements simultaneously.
To do this, you pass at least three arguments with the second one that specifies the number of items to delete and the third one that indicates the elements to insert.
Note that the number of elements to delete needs not to be the same as the number of elements to insert.
Suppose you have an array of programming languages with four elements as follows:
let languages = ['C', 'C++', 'Java', 'JavaScript'];
Code language: JavaScript (javascript)
The following statement replaces the second element by a new one.
languages.splice(1, 1, 'Python');
Code language: JavaScript (javascript)
The languages array now still has four elements with the new second argument is ‘Python’ instead of ‘C++’ .
console.log(languages); // ["C", "Python", "Java", "JavaScript"]
Code language: JavaScript (javascript)
The following figure illustrates the method call above.
You can replace one element with multiple elements by passing more arguments into the splice() method as follows:
languages.splice(2,1,'C#','Swift','Go');
Code language: JavaScript (javascript)
The statement deletes one element from the second element i.e., Java and inserts three new elements into the languages array. The result is as follows.
console.log(languages); // ["C", "Python", "C#", "Swift", "Go", "JavaScript"]
Code language: JavaScript (javascript)
In this tutorial, you have learned how to use the JavaScript Array splice() method to delete existing elements, insert new elements, and replace elements in an array.
Javascript replace element in array
Last updated: Dec 22, 2022
Reading time · 5 min
# Table of Contents
# Replace an Element in an Array in JavaScript
To replace an element in an array:
- Use the Array.indexOf() method to get the index of the element.
- Change the value of the element at the specific index.
- The value of the array element will get updated in place.
Copied!const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 if (index !== -1) arr[index] = 'z'; > console.log(arr); // 👉️ ['z', 'b', 'c']
We used the Array.indexOf method to get the index of the array element with a value of a .
Copied!const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); console.log(index); // 👉️ 0
We then replaced the element at that index with a new value.
Copied!const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 if (index !== -1) arr[index] = 'z'; > console.log(arr); // 👉️ ['z', 'b', 'c']
We check if the method didn’t return an index of -1 to be sure that an element with the specified value exists.
JavaScript indexes are zero-based, so the first element in an array has an index of 0 and the last element has an index of arr.length — 1 .
Alternatively, you can use the Array.splice() method.
# Replace an Element in an Array using Array.splice()
This is a three-step process:
- Use the indexOf() method to get the index of the element to be replaced.
- Use the Array.splice() method to replace the element at the specific index.
- The array element will get replaced in place.
Copied!const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 arr.splice(index, 1, 'z'); console.log(arr); // 👉️ [ 'z', 'b', 'c' ]
We passed the following 3 arguments to the Array.splice method:
- start index — the index at which to start changing the array.
- delete count — how many elements should be deleted from the array.
- item1 — the item to add to the array.
We set the start index to the index of the array element we want to replace.
Copied!const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 arr.splice(index, 1, 'z'); console.log(arr); // 👉️ [ 'z', 'b', 'c' ]
We set the delete count argument to 1 , so the Array.splice() method will remove the array element at the specified index and will add the provided third argument at the same index.
In practice, we remove the array element at the specified index and then insert a different value at the same index, so we end up replacing the array element.
An alternative approach is to use a basic for loop.
# Replace an Element in an Array using a for loop
This is a three-step process:
- Use a for loop to iterate for array.length iterations.
- Check if each array element is the one to be replaced.
- If the condition is met, replace the element at the index and break out of the for loop.
Copied!const arr = ['a', 'b', 'c']; for (let index = 0; index arr.length; index++) if (arr[index] === 'a') arr[index] = 'z'; break; > > console.log(arr); // 👉️ ['z', 'b', 'c']
We used a basic for loop to iterate over the array. On each iteration, we check if the current element is the one we want to replace.
Once we find and replace the element, we break out of the loop to avoid unnecessary work.
If you want to replace all array elements with the specified value, simply remove the break statement.
Copied!const arr = ['a', 'b', 'c', 'a', 'a']; for (let index = 0; index arr.length; index++) if (arr[index] === 'a') arr[index] = 'z'; > > console.log(arr); // 👉️ [ 'z', 'b', 'c', 'z', 'z' ]
We didn’t use a break statement, so we replaced all elements with a value of a with elements with a value of z .
An alternative solution is to not change the original array, but instead, create a new array containing the desired values.
Want to learn more about updating arrays in JavaScript ? Check out these resources: Update all Elements in an Array in JavaScript ,Update an Object’s Property in Array of Objects in JS.
We can use the Array.map() method to achieve this.
# Replace an Element in an Array using Array.map()
This is a three-step process:
- Use the Array.map() method to iterate over the array.
- Check if the current element is the one to be replaced.
- If the condition is met, return the replacement value, otherwise, return the original value.
Copied!const arr = ['a', 'b', 'c']; const newArr = arr.map(element => if (element === 'a') return 'z'; > return element; >); console.log(newArr); // 👉️ ['z', 'b', 'c'] console.log(arr) // 👉️ ['a', 'b', 'c']
The function we passed to the Array.map() method gets called with each element in the array.
In the example, we replace all array elements with a value of a , setting them to a value of z .
We didn’t change the contents of the original array and instead created a new array with the values we need. This is often easier to reason about and track in larger code bases.
You can also use the Array.forEach() method to replace the array elements in place.
# Replace an Element in an Array using Array.forEach()
This is a three-step process:
- Use the Array.forEach() method to iterate over the array.
- Check if each element is the one to be replaced.
- If the condition is met, replace the element with the replacement value.
Copied!const arr = ['a', 'b', 'c', 'a', 'a']; arr.forEach((element, index) => if (element === 'a') arr[index] = 'z'; > >); // 👇️ [ 'z', 'b', 'c', 'z', 'z' ] console.log(arr);
The function we passed to the Array.forEach() method gets called with each element in the array.
On each iteration, we check if the current element is the one to be replaced.
If the condition is met, we replace the element with the replacement value.
The forEach() method is useful if you need to replace all occurrences of the value in the array.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
JavaScript: Update/Replace a Specific Element in an Array
This quick and straightforward article shows you a couple of different ways to update or replace a specific element in an array in modern JavaScript.
Using array[index] syntax
You can directly access an element in an array using its index and update its value:
const games = [ 'Elden Ring', 'GTA 5', 'Horizon Forbidden West' ]; // Update the second element whose index is 1 games[1] = 'Pokemon Go'; console.log(games);
[ 'Elden Ring', 'Pokemon Go', 'Horizon Forbidden West' ]
If you don’t know the index of an element but already know its value, you can its index by using the indexOf() method. The example below will update the element whose value is Dog :
const animals = ['Chicken', 'Elephant', 'Dog', 'Cat'] const indexOfDog = animals.indexOf('Dog') if(indexOfDog > -1) < animals[indexOfDog] = 'Dragon' >console.log(animals)
[ 'Chicken', 'Elephant', 'Dragon', 'Cat' ]
Using the splice() method
The splice() method allows you to add or remove elements from an array. You can use it to replace an element by specifying the index, the number of elements to remove (which is 1 in this case), and the new element to add.
let myArray = [10, 20, 30, 40, 50]; // Replace the 4th element (whose index = 3) with 2500 myArray.splice(3, 1, 2500); console.log(myArray);