Sum excluding one element in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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]
raja
Published on 24-Feb-2021 05:32:17
Advertisements