In this tutorial, let’s look at how to replace an item in an array in JavaScript.
We’ll be looking at multiple methods, from
1. simple methods that directly use the index to,
2. pre-defined JavaScript methods like splice, fill and slice and finish things off with
3. roundabout methods that involve loops and string conversions.
So, let’s get into it now.
Directly replace with the element’s index
The simplest, and most straight forward method of replacing an item in a JavaScript array is by directly accessing it via its index and assigning a new value to it.
Look at the example below:
let fruits = ['Grapes', 'Apples', 'Banana']; console.log(fruits); //['Grapes', 'Apples', 'Banana'] fruits[1] = 'Orange s'; console.log(fruits); //['Grapes', 'Oranges', 'Banana']
In arrays, every element has an index, and these indices start from 0, and increment by 1 until length-1.
You can use these indices to access the elements in these arrays. For example, in the above example, fruits[0] will return ‘Grapes’ and so on.
Now, if you know the index of the element you want replaced, like we did in this example, we can access the current element using that index and re-assign a new value to it. It’s that simple!
Use the splice method
The previous method only works on a single element. If you want to replace multiple elements, you’ll need to do multiple assignments, either directly, or by using a loop.
Instead, you can use the splice method. This is a pre-defined method that’s used to remove or replace elements in an array.
The beauty of this method is that you can remove and replace multiple elements at the same time, starting from a given position. Look at the syntax below:
Array.splice(start_index, deletecount, newItem1, newItem2...);
As mentioned in the above syntax, you need to specify the starting index; that is, the index from which you want to splice the array. Then specify the deleteCount, which refers to the number of elements you want removed from the starting index.
Finally, you can list the number of new items you want added to the array, separated by commas.
Unfortunately, just like with direct assignment, to use the splice method as well, you need to know the index of the element you want replaced.
Look at the example below. We want to replace ‘Apples’ with ‘Oranges’. ‘Apples’ is in the 1st index, so our starting index is 1.
We only want to remove that element, so we’ve specified the deleteCount as 1 as well.
Since we only have 1 element to add to the array, we’ve specified just ‘Oranges’ as the 3rd argument, and we’ve gotten our desired result.
let fruits = ['Grapes', 'Apples', 'Banana']; fruits.splice(1,1,'Oranges'); console.log(fruits); //['Grapes', 'Oranges', 'Banana']
Use the indexOf method
If you know the exact element you want replaced, you can use the indexOf method instead of the index. This method returns the index of the first occurrence of the value you’ve specified while calling it.
In the example below, you can see that we’re looking for the index of the element ‘Apples’, which is 1.
Then, we’re checking if the index is not -1 (which is what you’ll get back if the element is not present in the array).
let fruits = ['Grapes', 'Apples', 'Banana']; let index = fruits.indexOf('Apples'); console.log(index); //1 if(index !== -1) { fruits[index] = 'Oranges'; } console.log(fruits);
As I mentioned, this method only returns the index of the first occurrence of the value. If the same value occurs more than once, the subsequent occurrences will be removed.
If you’d like to replace all of them though, you might want to use loops and manual replacement after comparisons. We’ll look at how to do this further down this tutorial.
Use findIndex
Instead of the indexOf method, you can use the findIndex method to find the index of the first occurrence of the value that matches the given condition.
This method automatically iterates through the array, and for every iteration, we’re checking if the current value is ‘Apples’. If it is, the program will return its index and store it in the ‘index’ variable, as shown below:
let index = fruits.findIndex((fruit) => fruit === 'Apples');
Manually loop through the array
The pre-defined methods are great, but manually looping through the array and replacing the elements have their place as well.
For example, if you want to replace every occurrence of a given value, then the best way to do that is by looping through the array, checking if the element has the value you’re looking for, and if it does, then replacing it.
We’ll be looking at the ‘for’ and ‘forEach’ loop in this section.
For loop
Using the ‘for’ loop to replace an item is quite straight forward. Iterate from 0 to length-1, and for every iteration of the loop, compare fruits[i], which is the current element of the iteration, to ‘Apples’, which is the value we’re looking for.
If the condition is true, replace fruits[i] with ‘Oranges’ and break from the loop.
for(let i = 0; i < fruits.length; i++) { if(fruits[i] === 'Apples') { fruits[i] = 'Oranges'; break; //can stop the loop and save resources } }
In the above example, we’re breaking out of the loop because we’re sure that there’s only going to be one occurrence of ‘Apples’ in the array.
If you’re not sure about that, and if you’d like every occurrence replaced, then get rid of the ‘break’ statement, and let the loop run till the end of the array.
forEach loop
The forEach loop was specifically created to loop through an array. For every iteration of the loop, you’ll get access to the current element, which can be named anything you want (we’ve named it fruit in our example), and the index of that element (which starts from 0).
Then, you can check the value and replace the one you want replaced, as shown below:
fruits.forEach((fruit,index) => { if(fruit === 'Apples') { fruits[index] = 'Oranges'; } });
Use the ‘map’ method
Just like we used the forEach loop, we can use the ‘map’ method to loop over our array and check for its value during every iteration so we can replace the necessary one.
This method loops over an array, and returns (and replaces) the elements based on a condition.
In our example, we’re checking if the current value is ‘Apples’. If it is, we’re returning ‘Oranges’. If not, we’re returning the current value as it is, as shown below:
//loops over array and replaces or changes elements based on conditions - return the change or same element - creates copy - so reassign to original array fruits = fruits.map(fruit => { if(fruit === 'Apples') { return 'Oranges'; } return fruit; });
Use more pre-defined array methods
Apart from using the straight-forward pre-defined methods like splice and indexOf, you can also do things in a roundabout manner with the concat, fill, map methods and more. Let’s look at them in this section.
Slice with array concatenation
The concat method can be used to concat arrays into a single array, and the slice method can be used to slice an array based on the given indices.
Look at the example below:
//arr.concat('New item').concat('new item'); //slice(starting_pos,ending_pos+1) fruits = fruits.slice(0,1).concat('Oranges',fruits.slice(2)); console.log(fruits); // ['Grapes', 'Oranges', 'Banana']
As you can see above in the comments, the slice method takes 2 arguments, where the first argument is the starting position of the slice (it’s included in the slicing), and the second argument is the index of the ending position of the slicing (this is not included in the slicing).
So, slice(0,3) will slice from 0 to 2 (3 elements) and leave out the element at the 3rd index.
For this method to work, we need to know the index of the element we want removed.
In our example above, we want to remove the element at the 1st index. So, concatenate slice(0,1) (just the first element) with ‘Oranges’, which will now be the new 2nd element, as we wanted.
Finally, concatenate all of this with fruits.slice(2), which will retrieve the elements from the 2nd index (3rd element) till the end of the array.
Slice with the spread operator
Instead of using the concat method, we can just directly place the sliced arrays, along with the new element, inside of a new array, as shown below:
fruits = [fruits.slice(0,1),'Oranges',fruits.slice(2)]; //[Array(1), 'Oranges', Array(1)]
The problem with the above approach is that the sliced arrays will be placed as it is, without extracting their element. That’s not what we want.
So instead, use the spread operator on the sliced arrays so the elements are retrieved, and then combine them with the new value, as shown below:
fruits = [...fruits.slice(0,1),'Oranges',...fruits.slice(2)]; console.log(fruits); // ['Grapes', 'Oranges', 'Banana']
Use the ‘fill’ method
You can modify the ‘fill’ method a little to replace the element we need as well.
In the fill method, the first argument refers to the value you want to fill the array with. If you leave things at that, then the same value will be used to fill (or replace) all the elements of the current array.
Instead, you can specify the starting and ending position of the fill, as shown below:
fruits.fill('Oranges',1,2); console.log(fruits); // ['Grapes', 'Oranges', 'Banana']
Just like with the ‘slice’ method, for the ‘fill’ as well, the starting position will be considered, but the ending position will not.
So, if the last 2 arguments of ‘fill’ are 1 and 2, then the fill will happen from 1 to (2 – 1 = 1), which is just the element at the 1st index, just like we wanted.
Use the string replace method (when you know the value)
Finally, an even more roundabout way of doing things is by converting our string to an array and replacing the first occurrence of our value directly from the string.
Convert array to string
Let’s first look at how to convert our string to an array. We can use the ‘join’ method to make this conversion.
This method takes an argument. This argument refers to the ‘connector’ between the elements.
In our example, we’ve given a single comma as the connector, so the resultant string is all the values of the array, separated by commas, as shown below:
let fruits = ['Grapes', 'Apples', 'Banana']; fruits = fruits.join(','); console.log(fruits); //Grapes,Apples,Banana
We’ve given a defining connector in this example because, after replacing the needed value, we need to split back the string into its original array state, and for this, we need to use this connector to know exactly where the split must happen.
Use the replace method on the string
Now that we have a string, we can use the ‘replace’ method to literally replace ‘Apples’ with ‘Oranges’, as shown below:
fruits.replace(‘Apples’,’Oranges’);
fruits = fruits.split(','); console.log(fruits); // ['Grapes', 'Apples', 'Banana']
Once replaced, we split the string back into an array by using the comma as the split condition.
That’s it! We’ve looked at multiple ways of replacing an item in an array in JavaScript, like
1. Directly using its index and assigning it a new,
2. Using pre-defined methods like splice, indexOf, fill, etc,
3. Manually looping through the array using the ‘for’, ‘forEach’, ‘map’ methods, and finally,
4. Converting the array to a string and replacing the needed value via the ‘replace’ method.