replace item in array javascript
The Most popular way to replace an element in an array is to use its index. If you know the index of the element you want to replace, you can update it.
const frameworks = [ 'Angular', // Index 0 'ReactJS', // Index 1 'VueJS', // Index 2 ] frameworks[0] = 'Angular' console.log(frameworks) // Output: [ 'Angular', 'ReactJS', 'VueJS']
replace item in array using indexOf
method
If you don't know the item's index you want to replace, you can use the JavaScript
indexOf
method to find it.
- The
indexOf
function helps you find the framework's index. - If the element doesn't present in the array, the index returned is
-1
.
const frameworks = [ 'Angular', // Index 0 'ReactJS', // Index 1 'VueJS', // Index 2 ] const findIndex = frameworks.indexOf('Angular') console.log(findIndex) // Output: 0 const nextJSIndex = frameworks.indexOf('NextJS') console.log(nextJSIndex) // Output: -1
const frameworks = [ 'Angular', // Index 0 'ReactJS', // Index 1 'VueJS', // Index 2 ] const lastIndex = frameworks.indexOf('VueJS') console.log(lastIndex) // Output: 2 if (lastIndex !== -1) frameworks[lastIndex] = 'NextJS' console.log(frameworks) // Output: [ 'Angular', 'ReactJS', 'NextJS'] console.log(frameworks[lastIndex]) // Output: 'NextJS'
For More Reference