
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sum Excluding One Element in JavaScript
Suppose we have an array of Integers like this −
const arr = [12, 1, 4, 8, 5];
We are required to write a JavaScript function that takes in one such array as the only argument.
The function should then return an array of exactly two integers −
First integer should be the smallest possible sum of all the array elements excluding any one element.
Second integer should be the greatest possible sum of all the array elements excluding any one element.
The only condition for us is that we have to do this using one and only one for loop.
For example −
For the above array, the output should be −
const output = [18, 29];
because the numbers excluded are 12 and 1 respectively.
Example
The code for this will be −
const arr = [12, 1, 4, 8, 5]; const findExtremeNumbers = (arr = []) => { let sum = 0; let min = Infinity; let max = -Infinity; for(let i = 0; i < arr.length; i++){ const curr = arr[i]; sum += curr; if(curr > max){ max = curr; } if(curr < min){ min = curr; }; }; return [sum - max, sum - min]; }; console.log(findExtremeNumbers(arr));
Output
And the output in the console will be −
[18, 29]