# HELP_Return Largest Numbers in Arrays

HELP_Return Largest Numbers in Arrays
0

#1

Tell us what’s happening:
Challenge: Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

Only the first array seems to have been sorted.
The result I’m getting is [5,13,32,1000]

``````function largestOfFour(arr) {
for (var i = 0; i < 4; i++){
arr[i].sort(function(a,b){
return b > a;
});
var newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
return newArr;
}
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36`.

#2

That is because you put the following inside the for loop:

``````   var newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
return newArr;
``````

As soon as a return statement is executed, the value on the right is returned and the function is exited. Exited means no more code in the function is executed. Your function only gets through 1 iteration before it returns newArr. So while arr[0] will be sorted which means arr[0][0] is the largest number, the other values in newArr will just be whatever the first element of each sub array was at the time of the return statement.

#4

@norawilson291 - There are many solutions to this challenge which are better than yours and the OP’s, but the purpose of my post was to answer the question posed. Instead of just posting a completely different solution unrelated to the OP’s, it would be a better to offer insight on what was wrong with his solution and/or offer a hint to how it could have been fixed. We try to take advantage of teachable moments when they arise. This is what makes FCC such a great community. We are all trying to help each other learn to write better code.

I will leave your post, but in the future, unless someone specifically requests alternate solutions, it is best just to help with their current solution.

Thanks.