HELP - Return largest number in array problem

Anybody know why this doesn’t pass the test? It returns the wanted output every time.

``````var storearr = [];

function largestOfFour(arr) {
for (var i = 0; i < arr.length; i++) {
var digitarr = arr[i].sort(function(a,b) {
return b-a;
});
storearr.push(digitarr[0]);
}
return storearr;
}

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);``````

The global `storearr` is being reused for all test cases without being reinitialized - best to avoid global variables - turn it into a local variable of the function - you can see what’s going wrong with `console.log`

Thank you! Solved!

I made this really simple in JavaScript.

``````function max(arr){
var max = arr[0];
for(var i = 1; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}
``````

It’s all about efficiency and minimal code.

1 Like

By the way, a little trick:

See how there’s Math.max() ? Well, it takes a variadic number of arguments, so for example

``````Math.max(1, 2) // 2
Math.max(3, -5, 1) // 3
``````

Are totally valid but you can’t pass an array to it. What you could do is:

``````// a) Use apply syntax, compatible with all browsers
Math.max.apply(null, [1, 2, 3]) // 3

// b) Use the ES6 spread operator
Math.max(...[1, 2, 3]) // 3
``````

So my solution is

``````const largestNums = xss => xss.map(xs => Math.max(...xs))
``````
2 Likes

@geekysmurf - Your solution does not correctly solve the challenge. Your solution returns the largest number of a single array, but does not return an array of the largest number in each sub-array.

function largestOfFour(arr) {
// You can do this!
var a = 0, max = 0, b = [];
while( a < arr.length){
for(var i = 0; i < arr[a].length; i++){
if(arr[a][i] > max){
max = arr[a][i];
}
}
b[a] = max;
max = 0;
a++;
}
return b;
}
Hope this code does find max in each sub-array and put each maximum number in a new array which is returned at last.

Wow! That’s one tidy solution!

This is indeed a very neat solution, but sadly ES6 is not available in the FCC interpreter (afaict) so you’d need to use a regular function and ‘apply’ to pass the tests.

``````function largestOfFour(arr) {
return arr.map(function(xs){
return Math.max.apply(Math, xs);
});
}``````