Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Difference between sum and product of an array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should calculate the sum of all numbers in the array and the product of all numbers. Then the function should return the absolute difference between the sum and the product.
Example
Following is the code −
const arr = [1, 4, 1, 2, 1, 6, 3];
const sumProductDifference = (arr = []) => {
const creds = arr.reduce((acc, val) => {
let { sum, product } = acc;
sum += val;
product *= val;
return {
sum, product
};
}, {
sum: 0,
product: 1
});
const { sum, product } = creds;
return Math.abs(sum - product);
};
console.log(sumProductDifference(arr));
Output
Following is the output on console −
126
Advertisements
