w3resource

JavaScript: Sum of the Two highest Numbers

JavaScript Math: Exercise-84 with Solution

Write a JavaScript program to calculate the sum of the two highest positive numbers in a given array.

Test Data:
([1,2,6,3,4,5,6,7]) ->13
([2,3,4,5]) -> 9

Sample Solution:

JavaScript Code:

/**
 * Function to find the sum of the two highest numbers in an array.
 * @param {number[]} nums - The input array of numbers.
 * @returns {number} - The sum of the two highest numbers in the array.
 */
function test(nums) {
  // Filter out negative numbers from the array, sort it in ascending order,
  // take the last two elements (the two highest numbers), and sum them.
  return nums.filter((el) => el >= 0) // Filter out negative numbers
    .sort((x, y) => x - y) // Sort the array in ascending order
    .slice(-2) // Take the last two elements (the two highest numbers)
    .reduce((acc, el) => acc + el); // Sum the two highest numbers
}

// Test cases
// Assign value to nums
nums = [1, 2, 6, 3, 4, 5, 6, 7];
// Print the value of nums
console.log("nums = " + nums);
// Find the sum of the two highest numbers in the said array
console.log("Sum of the two highest numbers of the said array: " + test(nums));
// Repeat the above steps for a different value of nums
nums = [2, 3, 4, 5];
console.log("nums = " + nums);
console.log("Sum of the two highest numbers of the said array: " + test(nums));

Output:

nums = 1,2,6,3,4,5,6,7
Sum of the two highest numbers of the said array: 13
nums = 2,3,4,5
Sum of the two highest numbers of the said array: 9

Flowchart:

JavaScript: Sum of the Two highest Numbers.

Live Demo:

See the Pen javascript-math-exercise-84 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Missing number from an array.
Next: Sum of the main diagonal elements of a square matrix.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.