I believe there’s a concept I’m not getting 'coz I really think this should work. Please help me understand what I’m missing. I already looked at the solution and I think the difference is where I placed my variables and the return statement. TIA!
function largestOfFour(arr) {
// You can do this!
let maxNumber = 0;
let newArr = [];
for (let i = 0; i < arr.length; i++) {
for (let x = 0; x < arr[i].length; x++){
if(arr[i][x] > maxNumber) {
maxNumber = arr[i][x];
newArr = arr[i];
}
}
}
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Put maxNumber between loops. Also you don’t need to assign value to newArray. You must to push it.
Your fixed code:
function largestOfFour(arr) {
// You can do this!
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let maxNumber = 0;
for (let x = 0; x < arr[i].length; x++){
if(arr[i][x] > maxNumber) {
maxNumber = arr[i][x];
}
}
newArr.push(maxNumber);
}
return newArr;
}
But i have question for you. What will happen if you have array with arrays which contains only negative numbers ?
I just realized, I’m not understanding the problem correctly. I was trying to get the array with the highest number, but I am supposed to get the highest numbers of each array into an array. I thought the problem was like the previous the challenge. I’ll try this again.
Ok. I think I understand now. Here’s my final code which looks a lot like the solution.
function largestOfFour(arr) {
// You can do this!
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let maxNumber = arr[i][0];
for (let x = 1; x < arr[i].length; x++){
if(arr[i][x] > maxNumber) {
maxNumber = arr[i][x];
console.log(newArr);
}
} newArr.push(maxNumber);
console.log(newArr);
}
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
And I wanted to answer this:
Yeah, it did fail with negative numbers, that’s why instead of let maxNumber = 0;, it had to be the 1st value in the inner array like so: let maxNumber = arr[i][0];. And this variable had to be between the for loops so that maxNumber resets to the 0 index of the array every iteration.
I also had some difficulty understanding why the inner for loop in the solution had to start at 1. But now I understand that it is because my maxNumber is now already the 0th index of that array, the 2nd for loop should be 1.
Just took me about 4 hours to understand this challenge. And I love it.