Are you looking for the most efficient and straightforward method to multiply numbers in an array sequentially?
Let's say we have an array with some values:
const nums = [1, 5, 12, 3, 83, 5];
Now, our goal is to calculate the product of all values in the array. This means multiplying them together like this: 1 * 5 * 12 * 3 * 83 * 5
I attempted to achieve this using the following code snippet:
const nums = [1, 5, 12, 3, 83, 5];
multiply(nums);
function multiply(nums) {
for(i = 0; i < nums.length; i++) {
result = nums[i] * nums[i];
console.log(result);
}
}
The above code resulted in operations like 1 * 1, 5 * 5, 12 * 12, etc., which is not the desired outcome. I believe I understand why it worked that way, but I am uncertain how to modify the code for the correct calculation.
So, what would be the optimal approach for tackling this type of problem?
Edit. For those who are new to this, consider using the solution below as it has shown to be effective:
Leo Martin provides the answer:
const nums = [1, 5, 12, 3, 83, 5]; console.log(multiply(nums)); // logging the return value of the function function multiply(nums) { let product = nums[0]; for (i = 1; i < nums.length; i++) { product = product * nums[i]; } return product; }
Lastly, here is a shorter version of the solution:
You can also utilize
Array.reduce
:const nums = [1, 5, 12, 3, 83, 5]; const result = nums.reduce((acc, val, index) => { if (index === 0) return val; acc = acc * val; return acc; }, 0); console.log(result);