if you want to use Math.max.apply
, you don’t need second for
repetition. Math.max.apply
already check each second level array element for you. Your code will be like this :
function largestOfFour(arr) {
// You can do this!
large = [];
for(i=0;i<arr.length;i++)
{
large = Math.max.apply(Math, arr);
}
return large;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
After remove for
repetition, look at this :
large = Math.max.apply(Math, arr);
you mention arr
. You won’t get any result because your program expect list of number but you give them list of array. To solve this, set your program to look at each subarray that contain number
large = Math.max.apply(Math, arr[i]);
Is it done ? not yet. This is your output so far :
[1001]
this is the requested output :
[5, 27, 39, 1001]
Why it happen ? In your program, instead of save every largest value, you replace it. You need to use push()
to save every new largest value
large.push(Math.max.apply(Math, arr[i]));
this is your final code :
function largestOfFour(arr) {
// You can do this!
large = [];
for(i=0;i<arr.length;i++)
{
//large = Math.max.apply(Math, arr[i]);
large.push(Math.max.apply(Math, arr[i]));
}
return large;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
I know it’s pretty confusing, Just mention if you need further explanation