How to use the indexOf() Method In Javascript
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' ]
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.