Tell us what’s happening:
I would like to understand why my code doesn’t work. I think logic is Ok. I could use one of the solutions suggested, but I really would like to understand why this doesn’t work. Math.max.apply is working fine because I test it in line 4. Thank you very much. Your code so far
function largestOfFour(arr) {
var arrAux=[];
var element=0;
console.log(Math.max.apply(null,arr[0]));
for (var i=0; i<arr.lenght; i++) {
element=Math.max.apply(null,arr[i]);
arrAux.push(element);
}
return arrAux;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36.
In this challenge, you are asked to find the largest element in each subarray of the function argument arr. I don’t see where in your code your are comparing the entries of each subarray to determine which is the largest.
Here you compare each entry to null, but not to each other.
According to the documentation I read, I understood that Math.max.apply just returned the max number in an array, so I tried to assign the max number on each internal array to “element” and then, to push it to the new array… In fact, I tried it in line 4 and it works just fine…
Huh, I’ve never seen Math.max.apply. That’s definitely not something I’ve seen in my experience, but I was wrong and it does work when the typo is fixed. My eyes went right over that .apply part, as I’m used to seeing Math.max(...someArray)
function largestOfFour(arr) {
const arrAux = [];
for (let i = 0; i < arr.lenght; i++) { // Typo here - lenght
let largestElement = Math.max.apply(null, arr[i]);
arrAux.push(largestElement);
}
return arrAux;
}
As a side note for style, I would use const and let, and I’d restrict your scope to the smallest number of lines that you need for each variable. I added those style tweaks to your code so you can see what that would look like.
Thank you for the suggestion. I see your code is way more clean and concise. About my mistake, the console never returned syntax error and I didn’t see it!.