Hey it’s my second time going through these exercises and I knew I had to nest a for loop but without looking at the solution too much I thought I’d just post this.
Seems my biggest issue is with how to run through a nested array with a nested for loop. I saw the answer has a different variable name etc. Can you explain?
Update: Thought it may be better to post the parts of answer I don’t understand in the code:
function largestOfFour(arr) {
var results = [];
for (var i = 0; i < arr.length; i++) {
var largestNumber = arr[i][0]; // why do we keep this 0 here?
for (var ii = 1; ii < arr[i].length; ii++) { // why do we start at 1 not 0?
if (arr[i][ii] > largestNumber) {
largestNumber = arr[i][ii];
}
}
results[i] = largestNumber; //
}
return results;
}
Your code so far
function largestOfFour(arr) {
var largestArr = [];// initialize a variable to hold the largest value
for (var i = 0; i < arr.length; i++) {
largestArr = arr[i].length;
for (var i = 0; i < arr[i].length; i++) // this is the part I don't understand
{
if (arr[i].length > largestArr) {
largestArr = arr[i];
}
}
return largestArr; // return the largest value
}
console.log(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 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36
.
Challenge: Return Largest Numbers in Arrays
Link to the challenge: