Return Largest Numbers in Arrays

This blog explains my solution to the Return Largest Numbers in Arrays, a Bonfire exercise from Free Code Camp. The goal of this exercise is to make an array that combines the largest number of each sub-array. This might be useful if you’re creating a list of the top scores made by footbal teams in a league, for example.

This tutorial is written for people who know a little about JavaScript but are not familiar with push() and reduce() methods. You might be new to JavaScript, curious about how these methods work, or interested in writing code that will return all the largest numbers in sub-arrays into a new array.

Initial Problem

The initial code that’s given looks like this:

Solution

First of all, start by declaring an empty array. I called mine “finalArray”. This will be the container to hold your final array - the largest number from each sub-array. Then make a variable to hold the highest number found in each sub-array. I called mine “largeNumber”, and set it equal to zero.

Next create a basic for loop. This will iterate through the Big array comprised of smaller sub-arrays. Inside the for loop, we’ll push the largeNumber variable into the empty finalArray.

In JavaScript, the push() method adds a new value to the end of an array, and returns the new length. In this case, it’s handy because it allows us to loop through the entire big array, and each time it finds a newly identified largeNumber, it’s pushed into and added to the end of our finalArray. Cool, huh?

Your code should now look like this:

Now it’s time to build our loop. We want our largeNumber variable to hold only one number - the largest number within the sub-array. We can find this by using the reduce() method.

The reduce method can be a little confusing but let’s just focus on simply comparing one value, which I’ll refer to as a, to another value, which I’ll call b. If one is greater than the other it will be returned. In a nutshell, reduce() converts a list of values, in this case a and b, into a single value.

In each loop, we set our largeNumber equal to one sub-array at a time. And the reduce method compares only two values at a time, as it iterates through the entire sub-array. And what's produced is the largest number of a sub-array.

The largest number of each sub-array gets pushed into the finalArray, one by one until there are no more sub-arrays to loop through. And in the end we return the finalArray. Pretty slick, right?

Finished Code

While writing arrays can be confusing, they’re a useful way to organize numbers within Javascript. And if you find yourself needing to organize groups of arrays, you may find the reduce() method to come in handy. It’s a simple way to reduce a list of values into a single number. Once again JavaScript has simplified our lives! (pun intended:)