-3
The question is basically this: We need a product function that takes an array of numbers and returns the product: the result of multiplying all the elements among themselves.
For example, product([1, 4, 7]) should return 28, which is 1 * 4 * 7.
-3
The question is basically this: We need a product function that takes an array of numbers and returns the product: the result of multiplying all the elements among themselves.
For example, product([1, 4, 7]) should return 28, which is 1 * 4 * 7.
6
You can use the rest operator for that reason:
function mult(...terms) {
let current = 1
for (const term of terms) current *= term
return current
}
console.log(mult(1, 4, 7))
If you want to use one array in the first parameter, simply swap ...terms for terms:
function mult(terms) {
let current = 1
for (const term of terms) current *= term
return current
}
console.log(mult([1, 4, 7]))
5
The array has a function reduce that returns a single value according to the existing elements.
The method
reduce()performs a functionreducer(provided by you) for each member of the array, resulting in a single return value.Example:
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // expected output: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // expected output: 15
Applying to your problem:
const multiplicar = (itens) => itens.reduce((acumulador, item) => acumulador * item);
console.log(multiplicar([1, 4, 7]));
2
You can use the for classic which is also compatible with Internet Explorer 11:
function produto(v){
var res = 1;
for(var x = 0; x < v.length; x++) res *= v[x];
return res;
}
console.log(produto([1, 4, 7]));
1
I think that will solve the case:
var result = [1, 4, 7].reduce( (a,b) => a * b );
-2
PROBLEM:
We need a product function that takes an array of numbers and returns the product: the result of multiplying all the elements among themselves.
For example, product([1, 4, 7]) should return 28, which is 1 * 4 * 7.
SOLUTION:
Although it comes from the manual of how not to ask questions applies in this case:Problem of posting code as image
Browser other questions tagged javascript array function
You are not signed in. Login or sign up in order to post.
because you used "var res = 1", not "0" ?
– Vanessa Dutra Da Silva
It begins in 1 because 1 is the neutral term of multiplication, also called the neutral element or identity element. See more in https://pt.wikipedia.org/wiki/Elemento_neutro
– Woss
If starting with zero, the multiplication result will always be zero, regardless of the numbers in the array
– hkotsubo