How to use Array.prototype.forEach In Javascript
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 ]
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.