# Return Largest Numbers in Arrays using Math.max

Return Largest Numbers in Arrays using Math.max
0

#1

Tell us what’s happening:
There is an issue on 4th line with the function. I did research to find out, and it has to do with variables and closures. What are some ways I can fix it without using a let declaration. Will this code work to solve the problem?

I’m trying to create algorithms on my own and so far I’ve been good (except I needed to refer to hints for factorialize a number and get help from the forum for check for palindromes
).

I’m sure I can come up with another algorithm to solve this problem, but I want this one to work where I use for loop and Math.max. Just need help with the format/reworking the code to make it work.

Please if someone can help me fix this code so it works. Thank you in advance!

``````
function largestOfFour(arr) {
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i]; i++) {
var maxNumber = arr[i][j].reduce(function (a,b) {
return Math.max(a,b);
});
return maxNumber;
}
}
}

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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36`.

#2

You have 3 errors there, but problem is that you return from inside loop before you get maxNumber for all array elements.
You need to collect maxNumber for all elements in variable and return it when main loop finish.

``````for (var j=0; j < arr[i]; i++) {
``````

there is missing .length on arr[i]

`````` var maxNumber = arr[i][j].reduce(function (a,b) {
``````

arr[i][j] is number, not array

#3

hi thanks for the response, appreciate it a lot. I decided to actually go a different route just so I can continue to progress to next problem.

But I’m stuck once again trying to create my own code. It looks to be working , as it found largest number for two of the test arrays (largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].)

but is not able to find it for the third: largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000]…

``````function largestOfFour(arr) {
var largestNumberArray = [];
for (var i=0; i < arr.length; i++) {
var largestNumber = arr[i][0];
for (var j=0; j < arr[i].length; j++) {
if (arr[i][j] > largestNumber) {
largestNumber = arr[i][j];
largestNumberArray[i] = largestNumber;
}
}
}
return largestNumberArray;
}
``````

#4

With your current solution, if the largest number of the subarrray is the first element, then largestNumberArray never gets assigned anything.

#5

wow what a simple thing to overlook. Thank you @randeldawson and @korzo!