Arrays everywhere! Why?! Well, arrays are pretty useful actually. In any case, today’s exercise, largest numbers in arrays, will require some more array intricacies in order to write a function that takes an array with several arrays inside it, and return a new array containing the highest number in each of these arrays. The problem explicitly states that there will be 4 arrays inside our SUPER ARRAY -this term is used by me and me only-, but we’ll take it a step further.
Let’s make it simple for once. Just kidding, let’s use reduce again, I know you’ll love it.
First of all, we’ll create the wrapping function and a simple loop to go over each array. In theory, this is what we want to achieve: loop over the arrays one by one, pushing the highest number in each of them into a new array. Finally, return this new array for greatness.
To achieve this, I’ll start by declaring an empty array, and a variable that will temporarily store the highest value in an array. Then, a simple for loop will go over each array, and the reduce method will get the highest number in the array and put it inside the highestValue variable. We’ll then push this value to the results array and close the for loop. Finally, we return the newly created array. As a side note, I used the word array 7 times in this paragraph.
function largestOfFour(arr) { var resultArray = [], highestValue = 0; for (var i = 0; i < arr.length; i++) { highestValue = arr[i].reduce(function(a, b){ return a >= b ? a : b; }); resultArray.push(highestValue); } return resultArray; }
This code does exactly what we want, and even goes a stop further and loops over any number of arrays instead of just 4. There are quite a few other ways to get this right, so why don’t you try solving this problem without using a for loop? Here’s a tip: FUNCTIONAL PROGRAMMING.
Remember to always test the code, give it some thought and try your own solutions, innovate and come out with strange ways to solve your problems. Good luck and code your brains out!