Home > Article > Web Front-end > Exclude the sum of an element in JavaScript
Suppose we have an array of integers like this -
const arr = [12, 1, 4, 8, 5];
We need to write a JavaScript function that accepts an array like this as the only argument.
The function should return an array containing exactly two integers -
The first integer should be the smallest possible array element of all but one element sum.
The second integer should be the largest possible sum of all array elements excluding any one element.
Our only condition is that we must use one and only one for loop to do this.
For example -
For the above array, the output should be -
const output = [18, 29];
because the excluded numbers are 12 and 1 respectively.
Code is -
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));
The output in the console will be -
[18, 29]
The above is the detailed content of Exclude the sum of an element in JavaScript. For more information, please follow other related articles on the PHP Chinese website!