Difference between sum and product of an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 11-Dec-2020 09:34:24
Advertisements