How to Modify all Array Elements in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20212 min read

Modify all Elements in an Array #

To change the value of all elements in an array:

  1. Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself.
  2. Use the index of the current iteration to change the corresponding array element.
index.js
const arr = ['a', 'b', 'c']; arr.forEach((element, index) => { arr[index] = element + index; }); console.log(arr); // ๐Ÿ‘‰๏ธ ['a0', 'b1', 'c2']

The function we pass to the Array.forEach method gets invoked with each element, its corresponding index and the entire array.

We use the index to change the value of the array element at the specific position.

We could have achieved the same result using a plain for loop, however this solution is more verbose and indirect.

index.js
const arr = ['a', 'b', 'c']; for (let index = 0; index < arr.length; index++) { arr[index] = arr[index] + index; } console.log(arr); // ๐Ÿ‘‰๏ธ ['a0', 'b1', 'c2']

It's a matter of personal preference, but in my opinion the forEach approach is more readable and intuitive.

Most experienced developers avoid mutating arrays and objects, instead they create new arrays containing the desired elements. To achieve this we can use the map method.
index.js
const arr = ['a', 'b', 'c']; const newArr = arr.map((element, index) => { return element + index; }); console.log(newArr); // ๐Ÿ‘‰๏ธ ['a0', 'b1', 'c2'] console.log(arr) // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

In the code snippet, we use the Array.map in a very similar way to how we used the forEach method, however this time we don't change the elements in the original array, instead we create a new array containing the modified elements.

Code gets very hard to follow and read if we mutate the contents of an array multiple times. In my experience, a better approach is to create a new array containing the elements we need.

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