I'm creating a function that takes an array of numbers and multiplies them but I haven't found a workable solution.
This is what I've gotten 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:MDN documentation with examples here . Basically reduce would work like this:
Where the
acumulador
stores the values we want it to save when we want it to save them. ThevalorInicial
, if not specified, takes the first value of the array (in this example: 1). In the case of multiplication, each iteration we are multiplyingacumulador
the value of each element, it would work as thetotal
question variable. The example without using the arrow function and using thereturn
, would be: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 onacumulador
it as we would with an object or an array.You have 3 errors:
length
total
to 1It would be like this:
The producer is the multiplication of all the elements of the array, therefore it is not necessary to perform a sum, then the result is multiplied from 1.
Another way to get the producer of an array is with a recursive method:
The code like this is much more simplified.
I hope I have contributed to solve the problem, greetings.
In case you do not want to multiply by the number 0, I leave you a solution:
use
filter
because in your question you put an if condition that no number is equal to 0 ->if(producto[f]!=0){
let myArray = [1, 2, 5, 77, 99, 7, 6, 9]
let multiplication = myArray.reduce((a, b)=> a * b) console.log(multiplication)