Update all the Elements in an Array using JavaScript

avatar

Borislav Hadzhiev

Sat Nov 20 20212 min read

banner

Photo by Ales Krivec

Update all the Elements in an Array #

To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values.

index.js
const arr = ['zero', 'one', 'two']; arr.forEach((element, index) => { arr[index] = element + index; }); // ๐Ÿ‘‡๏ธ ['zero0', 'one1', 'two2'] console.log(arr);
If you want to avoid changing the original array, scroll down to the next subheading.

The function we passed to the Array.forEach method gets called for each element in the array.

Each time, it gets passed the following 3 parameters:

  1. the element
  2. the index
  3. the array

On each iteration, we can use the index to update the value of the current array element.

Note that this changes the values in the original array in place.

An alternative solution, that doesn't mutate the original array is to use the Array.map method.

Update all the Elements in an Array using map() #

To update all the elements in an array:

  1. Call the map() method to iterate over the array.
  2. On each iteration, return the updated value for the array element.
  3. The map() method will return a new array, that contains the updated values.
index.js
const arr = ['zero', 'one', 'two']; const newArr = arr.map((element, index) => { return element + index; }); // ๐Ÿ‘‡๏ธ ['zero0', 'one1', 'two2'] console.log(newArr); // ๐Ÿ‘‡๏ธ ['zero', 'one', 'two'] console.log(arr);

The function we passed to the map() method gets called for each element in the array.

It gets passed the following 3 parameters:

  • the element
  • the index
  • the array

Whatever we return from the callback function gets added to the new array the map() method returns.

The map method does not mutate the original array, it returns a new array.

Which approach you pick is a matter of personal preference. I'd go with the map() method, because I find mutations difficult to reason about and track throughout a code base.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee