Home > Web Front-end > JS Tutorial > Exclude the sum of an element in JavaScript

Exclude the sum of an element in JavaScript

王林
Release: 2023-08-30 10:57:03
forward
802 people have browsed it

JavaScript 中排除一个元素的总和

Suppose we have an array of integers like this -

const arr = [12, 1, 4, 8, 5];
Copy after login

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];
Copy after login

because the excluded numbers are 12 and 1 respectively.

Example

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));
Copy after login

Output

The output in the console will be -

[18, 29]
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template