So i am new to JavaScript and currently stuck at solving Basic Algorithm problem, where an array consisting of largest numbers must be returned from an Array which consists of sub-Arrays.

If you look at the last test (the failing one) you have a peculiar difference from the previous one: negative numbers!

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

Now, looking at your function you have declared this variable:

var largestArray = [0,0,0,0];

As you can see, you are working under the assumption that 0 is the lowest a number it can get, but looking at the input example above the “largest” in the set is -3 and not 0.

My suggestion is re-think the whole largestArray functionality since it works under the assumption that 0 is the lowest possible number

@Marmiz is right, when you write a function you have to think about any possible input, of any size; they may be positive numbers, negative numbers, positive and negative mixed up etc. I would suggest you to use a built-in function, Math.max, with the spread operator. They are both explained in the curriculum. Good luck!

I believe there are other methods to solve this problem. Using Reduce and Math.max, where this problem doesn’t occur. Thank you. I will take what you said into account.

To be honest, those are possible way to solve it, but not only that.
There’s a simple, yet effective change you can make to your code that will make it work regardless of input, without changing any methods or adding any new one.
(no reduce, math.max/min…)

Hint: you don’t really need to compare the subarray values to the “lowest possible number allowed in Javascript”, but just among each other of the set.

function largestOfFour(arr) {
// we will return this
// we don't assume neither the quantity nor the bottom cap
var largestArray = [];
for(var i = 0; i < arr.length; i++){
// we loop inside each sub-array
// we start by saying that the "largest" for now is the first element in the array
// as we yet have to see the others
ver largestN = arr[i][0];
// we loop the sub-array starting from the 2nd element due to the previous assumption
for(var j = 1; j < arr[i].length; j++){
// we simply check which one is the largest
if(arr[i][j] > largestN ){
// and update the varaible
largestN = arr[i][j]
}
}
// at the end of the sub-array loop
// push into the result what we determined being the "largest"
largestArray[i] = largestN
}
// and finally return the result array
return largestArray;
}

Of course you could update the “result array” with each iteration where the condition is satisfied, but you also need to keep updating the variable (largestN) so it stays consistent

But this way you update two variables instead of one. For such a simple case it won’t really matter, but what if we have a billion long array and by chance is sorted from smallest to largest? we will update two varaibles a billion times, when we could have updated “only” one