Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply by number all ellements of an array with forEach in JavaScript

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.

like image 965
urukhai Avatar asked Jan 08 '23 17:01

urukhai


2 Answers

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.

like image 136
Vivin Paliath Avatar answered Jan 16 '23 05:01

Vivin Paliath


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

like image 44
Rick Hitchcock Avatar answered Jan 16 '23 07:01

Rick Hitchcock