How to replace an item from an array in JavaScript ?
Replacing an item from an array in JavaScript refers to the process of updating the value of an existing element at a specified index within the array with a new value, effectively modifying the array content.
Examples of replacing an item from an array in JavaScript
Table of Content
- Using Array Indexing
- Using the splice() Method
- Using array map() and filter() Methods
- Using the indexOf() Method
- Using Array.prototype.forEach
Using Array Indexing
In this method, we will use the array indexing and assignment operator to replace an item from an array.
Example: In this example, we have used array Indexing to replace items in the array.
let array = [1, 2, 3, 4, 5];
const index = 2;
const newValue = 10;
array[index] = newValue;
console.log(array);
Output
[ 1, 2, 10, 4, 5 ]
Using the splice() Method
The array type in JavaScript provides us with the splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index.
Syntax:
Array.splice(start_index, delete_count, value1, value2, value3, ...)
Note: Splice() method deletes zero or more elements of an array starting with including the start_index element and replaces those elements with zero or more elements specified in the argument list.
Approach:
- Array
list
is initialized with months. - Using
splice(1, 0, "February")
to add “February” at index 1. - Resulting array:
["January", "February", "March", "April", "June"]
. - Using
splice(4, 1, "May")
to replace “June” with “May” at index 4. - Final array:
["January", "February", "March", "April", "May"]
. - The modified array is logged to the console.
Example: Below are some example to illustrate the Splice() method:
function element_replace() {
// Initializing the array
const list = ["January",
"March",
"April",
"June"];
// splicing the array elements using splice() method
list.splice(1, 0, "February");
// expected output [January, February, March, April, June]
// splicing the output elements after the first splicing
list.splice(4, 1, "May");
console.log(list);
}
element_replace();
Output
[ 'January', 'February', 'March', 'April', 'May' ]
Using array map() and filter() Methods
Using map() to transform array elements and filter() to selectively include elements based on a condition, creating a new array with modified or filtered values.
Syntax:
ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_value
Approach:
- The code initializes an array
ele
with values [10, 20, 300, 40, 50]. - It finds the index of the first occurrence of the value 300 in the array.
- The value at the found index is replaced with 30.
- The modified array is logged to the console.
Example: Below are some example to illustrate the Splice() method:
function element_replace() {
const ele = Array(10, 20, 300, 40, 50);
ele[ele.map((x, i) => [i, x]).filter(
x => x[1] == 300)[0][0]] = 30
console.log(ele);
}
element_replace();
Output
[ 10, 20, 30, 40, 50 ]
Using the indexOf() Method
Using the indexOf() method finds the index of an element in an array, allowing you to perform operations based on its presence or absence.
Syntax:
const index = arr.indexOf('a');
Apporach:
- Find index: Use indexOf() method to locate the index of the element ‘a’.
- Check existence: If indexOf() doesn’t return -1, indicating existence.
- Replace: Replace element at found index with ‘z’.
Example: In this example, we will use the indeOf Method
const arr = ['a', 'b', 'c'];
const index = arr.indexOf('a');
if (index !== -1) {
arr[index] = 'z';
}
console.log(arr);
Output
[ 'z', 'b', 'c' ]
Using Array.prototype.forEach
Using Array.prototype.forEach, you can replace an item in an array by iterating over each element. Check if the current index matches the target index, and if so, update the value at that index. This method directly modifies the original array.
Example:
let arr = [1, 2, 3, 4, 5];
let index = 2; // Index of the item to replace
let newValue = 10;
arr.forEach((item, i, array) => {
if (i === index) {
array[i] = newValue;
}
});
console.log(arr); // [1, 2, 10, 4, 5]
Output
[ 1, 2, 10, 4, 5 ]