Recursive Method
In this approach, we will recursively visit each element of the array and multiply it with the product of all the previous elements to get a new product value till the current element.
Example: The below code example will explain to you the practical implementation of the recursive approach to solve this problem in JavaScript:
const arr1 = [8, 9, 3, 7, 5, 13];
const arr2 = [12, 9, 5, 18, 23];
const recursiveMultiply = (arr, ind) => {
if (ind === arr.length - 1) {
return arr[ind];
} else {
return arr[ind] * recursiveMultiply(arr, ind + 1);
}
};
console.log(recursiveMultiply(arr1, 0));
console.log(recursiveMultiply(arr2, 0));
Output
98280 223560
Time Complexity: O(n), n is the size of the passing array.
Space Complexity: O(n), n is the size of the passing array.
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: