Column of a matrix [array]

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]?

What have you tried?

1 Like
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