Tell us what’s happening:
Trying to work through this challenge. It’s a tough one, but I’m getting better. As it stands my loop is going through each part of the arrays one by one and comparing to see which is greater.
A variable “largest” is compared to the current iteration of the array, if the variable is larger it gets pushed to a new array. If the variable is less than the item in the array, the variable “largest” is then set to that amount.
There are several areas I’m getting hung up on. One is where , for example, 5 gets compared to 1. My if statement will return both true and false. 5 will get pushed to the new array AND 1 will be updated to the largest number. I’ve added plenty of plain text print outs to see what is going on during the code.
This confuses me. Without giving me the solution can anyone give me a hint as to what I’m not able to see.
Your code so far
function largestOfFour(arr) {
var largest = arr[0][0];
var largestArr = [];
console.log(`declaration: largest = ${largest}\n`)
for (let n = 0; n < arr.length; n++)
{
largest = arr[n][0]
console.log(`Outer loop start, current array items: ${arr[n]}\nlargest is set to first item = ${largest}\n............................................`)
for (let m = 0; m < arr[n].length; m++)
{
if (largest > arr[n][m])
{
largestArr.push(largest)
console.log(`current largest bigger than array item.\nPushed largest to new largestArr: ${largest}\n............................................`)
}
largest = arr[n][m]
console.log(`Current largest, not bigger than array item.\nNew largest: ${largest}\n............................................`)
}
console.log(`Outer loop end: largestArr items: ${largestArr}`)
}
arr = largestArr;
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function largestOfFour(arr) {
var largest = arr[0][0];
var largestArr = [];
console.log(`declaration: largest = ${largest}\n`)
for (let n = 0; n < arr.length; n++)
{
largest = arr[n][0]
console.log(`Outer loop start, current array items: ${arr[n]}\nlargest is set to first item = ${largest}\n............................................`)
for (let m = 0; m < arr[n].length; m++)
{
if (largest > arr[n][m])
{
largestArr.push(largest)
console.log(`current largest bigger than array item.\nPushed largest to new largestArr: ${largest}\n............................................`)
}
largest = arr[n][m]
console.log(`Current largest, not bigger than array item.\nNew largest: ${largest}\n............................................`)
}
console.log(`Outer loop end: largestArr items: ${largestArr}`)
}
arr = largestArr;
return arr;
}
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/106.0.0.0 Safari/537.36
Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays
Link to the challenge: