# Return Largest Numbers in Arrays - Code sorts numbers in new array

Tell us what’s happening:
The code almost works but i am obviously missing something.

``````largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
**THIS RETURNS [5, 27, 39, 1001]** INSTEAD largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
``````

it seems to sort the numbers for a reason i find muself unable to understand, any help appreciated

``````function largestOfFour(arr) {
var num = "" ;
var newArr = [];
for (var i = 0; i < arr.length; i++){
for (var x = 0; x < arr[i].length; x++){
if (num < arr[i][x]){
num = arr[i][x];
}
}newArr.push(num);
}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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36`.

In the test case of:

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

when i = 0, you assign num the value 27 when x = 1. At the end of the inner for loop num is still 27, so when you start the 2nd iteration of the outer loop (i = 1), num is still 27 and all the elements of the 2nd subarray are less than num, so your num = arr[i][x]; code never executes based on the if statement and then at the end of the 2nd iteration of the outerloop, you are pushing num (still 27) to newArr. You need to reset num to something else either before or after the inner for loop.

1 Like

THANK YOU!

That was of course correct, resetting num between the outer and inner loop did the trick.