How to multiply all numbers in an array using JavaScript
Quick tutorial on how to multiply all the elements in an array using iterative i.e loop and reduce method in JavaScript.
In this article, we will see how to multiply all the numbers in an array using JavaScript.
Let's say we have an array of numbers like this,
[2,2,3,4]
And we have to multiply all the numbers and give us the product as the return value.
So the output should be:
Input: [2,2,3,4] Output : 2*2*3*4 = 48
So using JavaScript, we will find the product of all the elements of an array using:
- for loop or
- Array.reduce() function.
Let's see each with an example.
Multiple numbers in an array using for loop
We can use the for loop in JavaScript to find the product of all the numbers in an array.
Example:
const arr = [2,2,3,4] const multiply = (arr) => { var pro = 1; for (i = 0; i < arr.length; i++) pro = pro * arr[i]; return pro; } console.log(multiply(arr)) // Output : 48
Here, in the above code, we have created a function called multiply, which takes an array as an argument.
And the function uses for loop to loop through each element in the array until the condition i < arr.length is met.
On each iteration of the loop, the multiplied value is stored in the variable pro . And the initial value of pro is 1 , as any number multiple with 0 is 0.
Once, the condition is met(i.e false) it returns us the product of the multiplied numbers.
Multiply all the numbers in an array using reduce()
The reduce() method runs a user-defined "reducer" callback function on each element of an array. It returns a single value after running the callback function on each element of the array.
Syntax:
reduce(callbackFn, initialValue)
callBackFn: The user-specified "reducer" function.
initialValue: It is the value that is passed to the function as the initial value.
So, let's use the Array.reduce() method to multiple numbers in an array.
const arr = [2,2,3,4] const pro = arr.reduce((a, b)=> a*b, 1) console.log(pro) // 48
Here, the initialValue is 1 and not 0, because any number multiple with 0 is 0.
And, (a, b) => a*b is the callback function.
Related Posts
Find the average of n numbers using JavaScript
Tutorial to write a JavaScript function to find the average of n numbers of items in an Array using JavaScript.
Best way - Split an array into half in Javascript
To divide an single array into half i.e into two different arrays without modifying the original array we can use Array.slice() method in JavaScript.
Merge Two Arrays and Remove Duplicates - JavaScript
Tutorial on how to merge two or more array and remove duplicates in JavaScript.
Fill array with incrementing numbers/ intergers using JavaScript
Find out how to fill an array with incrementing numbers/integers using JavaScript's for loop and Array.from() method with keys().
