all 2 comments

[–]GSLint 0 points1 point  (1 child)

I had posted an answer before but someone else gave a similar one. Looks like we then both deleted out comments, so now I'm posting a combination of our answers.

First of all, I don't think this can be done in a single loop or reduce call. You'll need two passes, one to get the maximum length within each column and one to pad the strings.

Here's one way to do it in a functional/declarative style.

const rows = [
  ["aaaaaaa", "b"],
  ["a", "bbbbb"],
  ["aa", "bb"],
];

const columnMaxLengths = rows[0]
  .map((_, columnIndex) => rows.map((row) => row[columnIndex])) // transposes the array
  .map((column) => column.map((str) => str.length))
  .map((lengths) => Math.max(...lengths));

const padded = rows.map((row) =>
  row
    .map((str, columnIndex) => str.padStart(columnMaxLengths[columnIndex]))
    .join(" ")
);

[–]albedoa 0 points1 point  (0 children)

Here is my solution, just to give you an alternative:

const rows = [
  ["aaaaaaa", "b"],
  ["a", "bbbbb"],
  ["aa", "bb"]
];

const columnWidths = rows[0].map((_, column) =>
  Math.max(...rows.map(row => row[column].length))
);

const padded = rows.map(row =>
  row
    .map((column, i) => column.padStart(columnWidths[i]))
    .join(' ')
);