I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.
function largestOfFour(arr) {
var one = arr[0];
var two = arr[1];
var three = arr[2];
var four = arr[3];
var newArr = [];
for (var i = 0; i < one.length; i++){
var oneLrg = 0;
if (one[i] > oneLrg){
oneLrg = one[i];
}
newArr.push(oneLrg);
}
return arr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]
You can have a look at this:
This post hasn't had any new updates in about 3 months, but I figured I would post my solution to this problem as it looks a bit different than most of the other solutions posted thus far. Figured someone might find it helpful!
I am using quite a few built in method functions( .forEach, .sort, .push, .shift) a quick google search will explain each of these fairly well if you are unsure of how they work. https://developer.mozilla.org is a great resource for these.
This function will take two numbers and return their maximum:
This function will take an array of numbers and apply the
greatest
function to each number in turn (using the.reduce( callbackFunction, initialValue )
method of arrays) to get the maximum value in the array:The
findMaximum
function can be simplified by just callingMath.max()
with all the array values (eliminating the need for thegreatest
function); like this:This function will take an array (of arrays) and call
findMaximum
on each element of it and return a new array containing those maximums (using the.map( callbackFunction )
method on an array):No doubt that @Austin Hansen and I are leveraging the same learning environment for this challenge: Free Code Camp.
Having just worked through this challenge myself (FCC calls them "Bonfires"), I figured I'd provide solution that heavily dovetails from @Oriol 's excellent ">" solution.
I've included a specific note about the code blocks because to us newbies (at FCC or elsewhere), the absence of such can give us fits for hours : )
https://jsbin.com/puweci/edit?js,console
FCC recognizes the follow solution which doesn't NOT leverage Array.push().
The problem here is that you're overwriting
oneLrg
at each loop iteration, and pushing it inside the same loop, so you're comparing each value to 0 and then, asone[i]
is bigger, saving it.Try this: