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.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Let’s talk about Recursion.

Event Loop in JS

React JS state management in Class Component vs in Functional Component

My Angular On Inheritance — Angular is Javascript Meta

Getting Started with Angular -01

Using CSS Modules In React App

A Brief Introduction to the Various Aspects of D3.js

Choosing the right Node.js Framework

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
Marcos Lipic

Marcos Lipic

More from Medium

The Commencement


Why the average note-taker should choose Roam

Choking on the patriarchy