# Return Largest Numbers in Arrays-why I am only passing three tests and not the last one?

Tell us what’s happening:

`function largestOfFour(arr) {
// You can do this!
var result = [];
for (var i = 0; i < arr.length; i++){
var largestNumber = 0;
for (var j = 0; j < arr[i].length; j++){
if (arr[i][j] > largestNumber){
largestNumber = arr[i][j];
}
}
result.push(largestNumber);
}

return result;
}

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

``````
`function largestOfFour(arr) {
// You can do this!
var result = [];
for (var i = 0; i < arr.length; i++){
var largestNumber = 0;
for (var j = 0; j < arr[i].length; j++){
if (arr[i][j] > largestNumber){
largestNumber = arr[i][j];
}
}
result.push(largestNumber);
}

return result;
}

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

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

Because you never account for negative numbers.

Look at the last test, the last array is

``````[-72, -3, -17, -10]
``````

The “largest” number there is `-3`,
However since you initialise `var largestNumber = 0;` the largest in that array will be `0` instead of `-3`

To sum it up

``````expected: [25, 48, 21, -3];
produced: [ 25, 48, 21, 0 ];
``````

Oh yes, I just realized the mistake, thanks so much for pointing out…I need to fix my assumption then, will try to fix it then, cheers

Thanks again, I examined my initializing and made some changes to account for the negative numbers in the resulting array, and here is the new code after which I passed all the tests ! cheers

``````function largestOfFour(arr) {
// You can do this!
var result = [];
for (var i = 0; i < arr.length; i++){
var largestNumber  = arr[i][0];
for (var j = 1; j < arr[i].length; j++){
if (arr[i][j] > largestNumber){
largestNumber = arr[i][j];
}
}
result.push(largestNumber);
}

return result;
}

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

``````

Great solution
Works like a charm.

Another approach that would work would be to sort the inner array and then picks the first element

For example:

``````// picks the largest Number in an arra
const largestN = (arr) => arr.sort((a, b) => b - a)[0];
``````

Then you can use the Array.map method to easily call that function on every entry of the array…

…and, voillà

``````// see above
const maxN = (arr) => arr.sort((a, b) => b - a)[0];

// call maxN on every entry of the array
const largestOfFour = arr => arr.map(a => maxN(a));
``````

Same result, different approach

1 Like