JavaScript provides several ways to replace an item in an array, depending on whether the index or value is known.
- Direct indexing is best when the position is known.
- splice() can replace an item at a specific index.
- indexOf() can find an item before replacing it.
Approach 1: Using Array Indexing
Array indexing allows you to directly replace an item by assigning a new value to its index. This modifies the original array.
let arr = [1, 2, 3, 4, 5];
const idx = 2;
const val = 10;
arr[idx] = val;
console.log(arr);
Output
[ 1, 2, 10, 4, 5 ]
Approach 2: Using splice() Method
The splice() method can replace one or more elements at a specific index.
let arr = [10, 20, 30];
arr.splice(1, 1, 25);
console.log(arr);
Output
[ 10, 25, 30 ]
Approach 3: Using indexOf() Method
The indexOf() method can find the position of a specific value, which can then be replaced using array indexing.
const arr = ['a', 'b', 'c'];
const idx = arr.indexOf('a');
if (idx !== -1) {
arr[idx] = 'z';
}
console.log(arr);
Output
[ 'z', 'b', 'c' ]