javascript – Multiply elements of an Array


I am creating a function that receives an array of numbers and multiplies them but I have not found a viable solution.

This is what I have achieved so far:

 var total = 0; var producto = [1,4,7]; function productoria(){ for (var f=0;f<producto.lenght;f++){ if(producto[f]!=0){ total = total + (producto[f]*total); } }return total; } console.log(productoria());


Using reduce() is really short:

const producto = [1,4,7];

const res = producto.reduce((p,c)=>p*c);


The MDN documentation with examples here . Basically reduce would work like this:

arr.reduce(callback(acumulador, valorActual), valorInicial)

Where the acumulador stores the values ​​that we want it to save when we want it to save them. The valorInicial , if we don't specify it, takes the first value of the array (in this example: 1). In the case of multiplication, each iteration we are multiplying the value of each element to the acumulador , it would work as the total variable of the question. The example without using the arrow function and using the return , would be:

 const producto = [1, 4, 7]; const res = producto.reduce(function (acumulador, valorActual){ acumulador = acumulador * valorActual; return acumulador; } ); console.log(res);

The arrow function allows us to omit the return and the {} . In this case, the final value is a single number, but we could define an object or an array as the initial value and operate on the acumulador as we would an object or an array.

Scroll to Top