Having a real hard time figuring out why this is failing every test in this challenge. I also get the “TypeError: Cannot read property ‘length’ of undefined” every time.
Your code so far
function largestOfFour(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let largest = arr[i][0];
for (let j = 0; j < arr[i].length; i++) {
if (arr[i][j] > largest) {
largest = arr[i][j];
newArr.push(largest);
}
}
}
return newArr;
}
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/87.0.4280.141 Safari/537.36.
So I’m not able to create the variable outside of the for loop and then alter its value inside of the loop? I was thinking I could set it to the first value in each array and then compare it to the next value and then make largest that newer, larger value if it fits the parameters.
function largestOfFour(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let largest = arr[i][0];
for (let j = 0; j < arr[i].length; j++) { // I'm guessing this is how you fixed that one?
if (arr[i][j] > largest) {
largest = arr[i][j];
newArr.push(largest); // Why is this here? Do you want to push each time you find a bigger number?
}
}
}
// A console log here might be helpful to illustrate what I mean
return newArr;
}
Yea I see what you mean. Right now I’m pushing to the newArr any time the next number is greater than the last, not that it is necessarily the largest in the subarray. I’m going to need to relook here. I’m struggling to find a way to only add to the array when it is the largest after iterating through the subarray all the way through. When I try moving my .push call around in the formula it isn’t getting any better.
Got it! Makes sense that this needs to go inside the for loop iterating between the subarrays but outside of the ones inside the subarrays. I really appreciate it.