How to use forEach method In Javascript
In this approach we use forEach method. With forEach we look at each number in the array, one after the other. for each number we multiply it with a running total.
Example: Below example uses forEach method to multiply the elements of an array.
function multiplyArray(arr) {
let result = 1;
arr.forEach(num => {
result *= num;
});
return result;
}
let array = [1, 2, 3, 4, 5];
console.log(multiplyArray(array));
Output
120
Time complexity: O(n)
Space complexity: O(1)
Multiply the elements of an array in JavaScript
We will be given an initial array and we have to multiply all the elements of the array with each other to find a final product.
Examples:
Input: arr = [1, 2, 3, 4, 5];
Output: 120
Explanation: 1 * 2 * 3 * 4 * 5 = 120
Input: arr = [11, 12, 13, 14, 15]
Output: 360360
Explanation: 11 * 12 * 13 * 14 * 15 = 360360
There are three ways available in which we can solve this problem in JavaScript:
Table of Content
- Recursive Method:
- Iterative Method:
- Using the in-built methods:
- Using forEach method
- Using the Math Object: