

- 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
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]
- Related Questions & Answers
- JavaScript One fourth element in array
- Maximum Subarray Sum Excluding Certain Elements in C++
- Maximum sum subarray removing at most one element in C++
- Maximum Subarray Sum Excluding Certain Elements in C++ program
- Sum all similar elements in one array - JavaScript
- Sum identical elements within one array in JavaScript
- Common element with least index sum in JavaScript
- Find longest string in array (excluding spaces) JavaScript
- Excluding extreme elements from average calculation in JavaScript
- Average of array excluding min max JavaScript
- Maximize the maximum subarray sum after removing at most one element in C++
- Sum up a number until it becomes one digit - JavaScript
- Finding sum of every nth element of array in JavaScript
- Reduce sum of digits recursively down to a one-digit number JavaScript
- Reduce an array to the sum of every nth element - JavaScript
Advertisements