Summing the Two Highest Values

Photo by Crissy Jarvis on Unsplash

In today’s coding challenge, bigger is better. We are tasked with returning the sum of the two largest values in an array. So let’s jump into it.

First we are going to use the Math.max method to find the max value in the value in the array. But using it directly on the given array won’t work. What we can do is utilize the spread operator.

The spread operator expands the array and allows the method to identify the max value in the given assortment of elements.

With the max value in the array stored in a variable, we now need to find the second largest value in the array. This can be done by removing the max value we just identified from the array, and then finding the max value inside this new array.

This plan of action can be achieved by finding the index that the max value we identified is at, and then removing that index from the array. We can use the findIndex method on the array, finding the index where the element equals the variable we created which is equal to the max value in the array. The result of this operation should be saved to a variable called maxIndex.

Now we can splice the arr, removing one element, being that element at the index saved to the maxIndex variable.

At this point we can repeat the initial operation we conducted on the array, but this time to the new spliced array. Use Math.max on the array while also using the spread operator.

With both the highest value and the second highest value now identified, we can finally return the summation of the two values. Below is the function with an example input.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store