Bonfire: Return the Largest Numbers in an Array Solution

Let’s take a look at today’s Bonfire challenge, returning the largest numbers in an array. I was a bit thrown by this one, honestly, because something about numbers just intimidates me. So let’s approach this one slowly. First of all, here’s what Free Code Camp gives us:

function largestOfFour(arr) {
 // You can do this!
 return arr;
 }
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");

We can do this.

Approaching the Problem

Well, first thing, what we have isn’t a simple array where we can just do a single simple for loop and return the largest number for one array. We have to deal with all four arrays and return the largest among the numbers in each of the four arrays.

So my original plan to use a simple for loop is going on the backburner. The best/worst part about about these Bonfires is that they never test your solution on a straightforward case so that you have to think about your situation a bit more.

So here’s my thought process.

  1. I need an empty array to hold the largest of each array so I have something to return, and I need a variable to hold the largest number from each array too. So that’s one empty array I’m creating, and one empty variable.
  2. What I want to do is loop through the arrays inside of the largestOfFour arrays so I’ll need one for loop to go through largestOfFour then loop through each of the four arrays within.
  3. I then need to write another for loop that goes through each of the numbers inside of each of the four arrays. So I’m going down two levels of loops because we have arrays inside of largestOfFour array.
  4. I need to compare or sort the numbers inside of the array of numbers and determine the largest one. The largest one should be sent to the empty variable and then pushed to the empty array I created in step 1.

It seems a little convoluted to me, but the only ideas I had involved for loops, and looping while inside of a loop. I was sure there were other options out there, and I did find some to lead me to my eventual solution for this Bonfire.

Finding the Largest Numbers With For Loops

I kind of had to take it slow with this one because 1) numbers intimidate me, and 2) Loops inside of other loops to deal with arrays inside of other arrays make me frustrated because it can get so messy. And the most succinct alternate solution I found made me wish I’d thought of it first. Wulkan.me has it posted: here.

OK, without further ado, the first thing I did was the easiest possible thing. Small steps:

function largestOfFour(arr) {
var largestNumberArray = [];
var highestNumber = 0;
}

I defined an empty array to hold my largest numbers, and a variable to hold my highest number from each of the four arrays in largestOfFour. Now that the easy part is done, I’m going to write my first for loop:

function largestOfFour(arr) {
var largestNumberArray = [];
var highestNumber = 0;

for (var i = 0; i < arr.length; i++) {

largestNumberArray.push(highestNumber);

} 

return largestNumberArray;
}

OK. So I’ve written a really simple for loop up there, and most of us should be familiar with it by now. But what it’s set up to do is use i as a variable to iterate through the arr property. Arr being the four arrays present in largestOfFour. It iterates through all four because it detects how many arrays exist in arr using .length.

Inside of the for loop, I have my highestNumber variable being pushed into the empty largestNumberArray. Push() is one of those methods we haven’t talked about yet. So let’s deal with that now before we get into another method we haven’t yet seen.

The Push() Method

Push() is seen in a lot of programming languages and Javascript is one of them. Its function is usually the same across the board in that it’s used to add something to something else. Typically in Javascript, we use push() to add a value to the end of an array and returns its value.

So in this case, when we push the highestNumber onto largestNumberArray, we’re really adding whatever highestNumber happens to be into largestNumberArray. Ultimately what we’ll get from this is an array of the largest numbers in each of the arrays inside largestOfFour. Then we return the largestNumberArray after its had the largest numbers pushed to it.

Getting Back to the Loops

So, believe it or not, that was still the easy part. The next thing I have to do is evaluate all the numbers within each of those four arrays inside largestOfFour to determine which one is the largest. Now, I could write another–really messy–for loop, but thinking about it this whole time made me kind of sick. I did some research instead and got to a solution that seemed to be repeated over and over again: use reduce(). So here we go:

function largestOfFour(arr) {
var largestNumberArray = [];
var highestNumber = 0;

for (var i = 0; i < arr.length; i++) {

highestNumber = arr[i].reduce(function(a,b) {
if (a > b) {
return a;
} else {
return b;
}
});
largestNumberArray.push(highestNumber);

} 

return largestNumberArray;
}

Oh my gawd, what is going on up there? In this example, we use reduce() to evaluate the highest number using a function and if conditional that evaluates if value a (one number in the array) is greater than value b (another number in the array). Then, we’ll take the higher value from our conditional, send it through our reduce() method so we only end up with one value and slap it into highestNumber. From highestNumber, we’re going to make it throw its value into largestNumberArray so we can build a list of the highest numbers to validate this exercise.

Still confused about reduce()? Let’s find out what it is!

The Reduce() Method

I was going to link to the MDN documentation for this one too, but after actually reading it myself, the whole thing went backwards in my head. Truthfully, the documentation for any language isn’t always the most understandable thing out there–and it’s not just because it’s dry reading. Instead, I found this excellent, succinct explanation of reduce() that explains much better what it does and why we’re using it.

Essentially, we are reducing all the values within the array into one value that we can use. Any time you need to reduce a list of values to just one, reduce() might be just what you’re looking for.

The For Loop Solution Final

Here’s the final code.

function largestOfFour(arr) {
var largestNumberArray = [];
 var highestNumber = 0;
for (var i = 0; i < arr.length; i++) {
 highestNumber = arr[i].reduce(function(a, b) {
 if (a > b) {
 return a;
 } else {
 return b;
 }
 });
 largestNumberArray.push(highestNumber);
 }
 return largestNumberArray;
 }
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Run that and it’ll validate. Yippee! We did it!

Resources:

CPlusPlus on Ternaries
These magnificent people and C++ can explain so much of JS.

Reduce() on MDN
Kind of confusing explanation of reduce(), but perhaps it’s just me.

Gorka Hernandez, Find the Largest Number in an Array
Once again, Gorka has an excellent solution that I referenced, and it is using a nicer looking ternary operator instead of my if conditional.

StackOverflow, Finding Largest Number
StackOverflow discussion on finding the largest number in an array. The accepted answer is an interesting approach, a little heavy for me, but looks nice nonetheless.


3 comments on “Bonfire: Return the Largest Numbers in an Array Solution

  1. Alexander Zachreson on

    I did it with .map

    function largestOfFour(arr) {

    var ordArr = arr.map(function(val){

    val.sort(function(a,b){

    return b-a;});

    return val[0];});

    return ordArr;

    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *