For example, how do I achieve the following without iterating over the array?
var a = [1, 2, 3] * 5; // a should equal [5, 10, 15]
As stated in Docs:
The
map()
method creates a new array with the results of calling a provided function on every element in the calling array.
In my opinion, .map()
is more suitable if someone wants to create a new array based on input values from the current array.
However, if someone wants to modify the array in place, .forEach()
seems a better choice.
In ES6 we may use:
Following code will modify a given array arr
in place (without creating a new one):
arr.forEach((value, index) => {arr[index] *= 5});
Demo:
var arr = [1, 2, 3];
var scalar = 5;
arr.forEach((value, index) => {
arr[index] *= scalar;
});
console.log(arr);