How to print an aligned matrix of numbers in Node.js

1 Answer

0 votes
function printAlignedMatrix(matrix) {
    const columnWidths = matrix[0].map((_, colIndex) =>
        Math.max(...matrix.map(row => String(row[colIndex]).length)
    ));

    matrix.forEach(row => {
        let rowStr = '';
        row.forEach((cell, colIndex) => {
            const formattedCell = String(cell).padStart(columnWidths[colIndex]);
            rowStr += formattedCell + '  '; 
        });
    
        console.log(rowStr);
    });
}

const matrix = [
  [1,   12,    123],
  [45,  4567,  45678],
  [678, 67890, 1234567],
];

printAlignedMatrix(matrix);




/*
run:

  1     12      123  
 45   4567    45678  
678  67890  1234567  

*/

 



answered Nov 2, 2023 by avibootz

Related questions

1 answer 141 views
1 answer 125 views
1 answer 126 views
1 answer 162 views
1 answer 111 views
1 answer 149 views
1 answer 141 views
...