How to use the in-built methods In Javascript
There are some in-built array methods available in JavaScript which we can use to iterate through the array elements and make changes in their values by passing a callback function inside them. We will use the map() and the reduce() in-built methods in this approach to multiply the elements of an array.
Example: The below code example will explain the use of the in-built JavaScript methods to multiply the elements of an array:
let arr1 = [8, 9, 3, 7, 5, 13];
let arr2 = [12, 9, 5, 18, 23];
let mapRes = 1;
arr1.map((currItem) => {
mapRes *= currItem;
});
const reduceRes = arr2.reduce((res, currItem) => res *= currItem);
console.log(mapRes);
console.log(reduceRes);
Output
98280 223560
Time Complexity: O(n), n is the size of the passing array.
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:
Contact Us