The below solution only works for largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])
function largestOfFour(arr) {
// You can do this!
var temp = [];
for (var i = 0;i < arr.length;i++){
for (var j = 0;j < arr[i].length;j++){
if (arr[i][j] > temp[i]){
temp[i] = arr[i][j];
}
}
}
return temp;
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
It fails for the other numbers. I believe the reason for this is that i am using temp[i] instead of creating a new variable for the largest number and then using temp[i] to add the largest number. The below code works. My question is that: why can i not use temp[i] directly, why do i need to create a seprate variable largestNumber? why does it work for the first solution?
For example:
for (var i = 0;i < arr.length;i++){
largestNumber = 0
for (var j = 0;j < arr[i].length;j++){
if (arr[i][j] > largestNumber){
largestNumber = arr[i][j];
}
}
temp[i] = largestNumber;
}
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays