How to convert matrix (2D Array) of numbers to string in Node.js

1 Answer

0 votes
function convertMatrixToString(matrix) {
    let sizesarr = Array(matrix[0].length).fill(0)

    const result = matrix
        .map(a => a.map((val, i) => {
            const str = val.toString();
            if (sizesarr[i] < str.length) { 
                sizesarr[i] = str.length;
            }
            return str;
        }))
        .map(a => a.map((str, i) => str.padEnd(sizesarr[i])).join(' '))
        .join('\n');

    return result.trim();
}

const matrix = [
    [ 4,  7,  9, 18, 29],
    [ 1,  9, 18, 99,  4],
    [ 9, 17, 89,  2,  7],
    [19, 49,  6,  1,  9]
];

const str = convertMatrixToString(matrix);

console.log(str);

 
 
 
/*
run:
 
4  7  9  18 29
1  9  18 99 4 
9  17 89 2  7 
19 49 6  1  9
 
*/

 



answered Jul 14, 2024 by avibootz

Related questions

...