I have an array of numbers:
var array = [ 23, 67, 120, 170, 200, 212, 350 ];
and I want to scale down by 20% each of the element of the array.
I used array.forEach(function(item) {item * 0.8;});
, but it did nothing. I tried also var scaledArray = array.forEach(function(item) {item * 0.8;});
, but the result was undefined.
forEach
invokes the provided function against each element in the array; it does not return a new array with modified values (that come from calling the provided function against each element). What you want to use is map
:
array = array.map(function(element) {
return element * 0.8;
});
This will map every element of the array according to the mapping function that you have provided, and return a new array that consists of those mapped values.
If you want to keep the original array around, you can simply assign the result of map
to a different variable:
var scaledArray = array.map(function(element) {
return element * 0.8;
});
You could do both of these with forEach
like:
array.forEach(function(element, index, _array) {
_array[index] = element * 0.8;
});
and:
var scaledArray = [];
array.forEach(function(element, index) {
scaledArray[index] = element * 0.8;
});
But I'm sure you'll agree that the map
version is much more elegant and idiomatic.
Here's how to do it using forEach
:
var array = [ 23, 67, 120, 170, 200, 212, 350 ]
array.forEach(function(val, idx) {
array[idx]= val * 0.8;
});
alert(array.join('\r'));
Array.prototype.map()
is generally the more straight-forward solution, but it may actually be slower than Array.prototype.forEach()
for something like this, because forEach
can modify the array in-place:
http://jsperf.com/foreach-v-map
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With