To update all elements in an array using JavaScript, you can follow the steps below:
- Utilize the
Array.forEach()
method to iterate over the array. This method takes a callback function as an argument, which receives the array element, its index, and the array itself. - The callback function is executed for each element in the array, starting from the first element.
- Inside the callback function, modify the corresponding array element using its index.
Here's an example:
const birds = ['🐦', '🦅', '🦆', '🦉']
birds.forEach((bird, index) => {
birds[index] = `${bird} -> ${index}`
})
console.log(birds)
// Output: [ '🐦 -> 0', '🦅 -> 1', '🦆 -> 2', '🦉 -> 3' ]
The Array.forEach()
method was introduced in ES6. It executes the provided callback function once for each element in the array, in ascending order. Empty array elements are not processed by the callback function.
If you prefer not to modify the original array and instead create a new array with the updated elements, you can use the Array.map()
method:
const original = ['zero', 'one', 'two']
const updated = original.map((item, index) => {
return `${item} -> ${index}`
})
console.log(updated)
// Output: [ 'zero -> 0', 'one -> 1', 'two -> 2' ]
console.log(original)
// Output: [ 'zero', 'one', 'two' ]
The Array.map()
method invokes the provided callback function for each element in the array. It doesn't modify the original array and instead relies on the callback function's results to create a new array.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.