Languages
[Edit]
EN

JavaScript - change values in array during foreach

0 points
Created by:
Reilly-Collier
860

In this article, we would like to show you how to change values in array during foreach in JavaScript.

Quick solution (ES6):

// ONLINE-RUNNER:browser;

const letters = ['a', 'b', 'c'];

letters.forEach((element, index, array) => array[index] = 'x');

console.log(letters); // [ 'x', 'x', 'x' ]

 

Alternative solution (ES5)

In this example, we alternatively use forEach() with a second argument (context), which will be used as the value of this in each call to the callback function.

// ONLINE-RUNNER:browser;

var letters = ['a', 'b', 'c'];

letters.forEach(function(element, index) {
    this[index] = 'x';
}, letters);

console.log(letters); // [ 'x', 'x', 'x' ]

Warning:

This solution won't work with arrow functions.

 

References

  1. Array.prototype.forEach() - JavaScript | MDN

Alternative titles

  1. JavaScript - change values in array when doing foreach
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join