urukhai
urukhai

Reputation: 95

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.

Upvotes: 4

Views: 5474

Answers (4)

Vivin Paliath
Vivin Paliath

Reputation: 95558

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.

Upvotes: 8

Mau Di Bert
Mau Di Bert

Reputation: 59

You could use map which is straight-forward but if you want to work with forEach, be aware:

  • .forEach(function() { <code> }) is equivalent to (...) { <code> }..

You are multiplying numbers but not doing anything with those numbers. You could change the actual array you're working on but should assign that operation to the array. (I've also added .toFixed(2) to round the result to 2 decimal places and as the result is a string, added Number() to the whole result.

let array = [ 23, 67, 120, 170, 200, 212, 350 ];
array.forEach ( function(x,i) {
array[i] = (x * .8).toFixed(2);
console.log(array); 
});

Upvotes: 0

marsh
marsh

Reputation: 1441

Use map instead of forEach:

var arr = array.map(function(item) {return item * 0.8;})

The map method creates a new array with the results of calling a provided function on every element in this array, forEach doesn't create a new array.

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

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

Upvotes: 1

Related Questions