- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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));

Following is the output on console −

126

- Related Questions & Answers
- Difference between product and sum of digits of a number in JavaScript
- Absolute difference between sum and product of roots of a quartic equation?
- Difference between sum of square and square of sum in JavaScript
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?
- Difference Between Product and Process
- Product sum difference of digits of a number in JavaScript
- Find N integers with given difference between product and sum in C++
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Product of all other numbers an array in JavaScript
- Finding product of an array using recursion in JavaScript
- Difference between Product and Process in software development
- Difference between numbers and string numbers present in an array in JavaScript
- Compute cartesian product of elements in an array in JavaScript
- Subarrays product sum in JavaScript
- Subtract the Product and Sum of Digits of an Integer in C++

Advertisements