function largestOfFour(arr) {
let newArr = [];
for(let i = 0; i < arr.length; i++){
let max = 0;
for (let j = 0; j < arr[i].length; j++){
if (arr[i][j] > max){
max = arr[i][j]
}
}
newArr.push(max)
}
return newArr
}
console.log(largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]]));
// [ 5, 27, 39, 1001 ]
I solved this Freecodecamp challenge, pushing the largest(row) number in each array into the newArr.
How can i make the code be printed in a column and get this output [1000, 1001, 857, 39]?
for (let j = 0; j < arr[i].length; j++){
if (arr[i][0] > max){
max = arr[i][0]
}
}
newArr.push(max)
this…
Why are you hard coding 0? You needed needed a nested loop to go through the rows, so you will similarly need a nested loop to go through columns instead.
I though it should start looping from 00 - 01 - 02 - 03 and run column loop through. using arr[i] [0] only print the second column
You want the maximum value of each column, right?
To do that, you need to loop through every row of each column. You need a nested loop for that.
Your original code is actually close to doing what you want, but it visits every column of each row. You want the other way around.
1 Like
for(let i = 0; i < arr.length; i++){
let max = 0;
for (let j = 0; j < arr[i].length; j++){
if (arr[j][i] > max){
max = arr[j][i]
}
}
newArr.push(max)
}
return newArr
}
Thank you
system
Closed
February 12, 2023, 9:40am
8
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.