The best and the easiest way to multiply array numbers sequentially
I have got an array with some values:
const arr = [1, 5, 12, 3, 83, 5];
Now I want to get the product of all values from arr. It should works like this: 1 * 5 * 12 * 3 * 83 * 5
I have tried with this code:
const arr = [1, 5, 12, 3, 83, 5];
multiply(arr);
function multiply(arr) {
for(i = 0; i < arr.length; i++) {
product = array[i] * array[i];
console.log(product);
}
}
This code above works like this: 1 * 1, 5 * 5, 12 * 12, 3 * 3, 83 * 83, 5 * 5 and that is not result that I need. I think I know why it works like this but I'm not sure how to write code that I need.
So what's the best option for this kind of tasks?
Edit. For non-experienced people looking here in future this is the best option that we've found:
Leo Martin answer:
const array = [1, 5, 12, 3, 83, 5]; console.log(multiply(array)); // we log function return value function multiply(array) { let score = array[0]; for (i = 1; i < array.length; i++) { score = score * array[i]; } return score; }
and also the shorter version:
By the way, you could use
Array.reduce
:const array = [1, 5, 12, 3, 83, 5]; const result = array.reduce((acc, value, index) => { if (index === 0) return value; acc = acc * value; return acc; }, 0); console.log(result);
Just move console.log
outside for
body:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
By the way, you could use Array.reduce
:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);