Align Columns - freeCodeCamp

What is your hint or solution suggestion?

Link to the challenge:

Hi everyone,

I’ve been tackling the “Align Columns” challenge from Rosetta Code and wanted to share a JavaScript solution that dynamically aligns text across different columns based on a specified alignment (left, right, or center).

Here’s the formatText function that takes an array of strings as input and an alignment argument. This function handles cases where input text lines may or may not have trailing dollar characters. It also ensures that all columns share the same alignment, and any consecutive space characters adjacent to the end of lines are considered insignificant for the task.

The code is as follows:

/* jshint esversion: 6 */
function formatText(input, alignment) {
  const delimiter = '$';
  // Split the input into rows and fields
  const rows = => line.split(delimiter));
  // Find the maximum number of columns across all rows
  const maxCols = Math.max( => cols.length));
  // Normalize rows to have the same number of columns
  const normalizedRows = => {
    while (cols.length < maxCols) {
    return cols;
  // Calculate the maximum width for each column
  const colWidths = Array.from({ length: maxCols }, (_, i) => {
    return Math.max( => row[i].length));
  // Function to align fields within their column based on alignment argument
  const alignField = (field, width, align) => {
    switch (align) {
      case 'left':
        return field.padEnd(width, ' ');
      case 'right':
        return field.padStart(width, ' ');
      case 'center':
        const totalPadding = width - field.length;
        const leftPadding = Math.floor(totalPadding / 2);
        return ' '.repeat(leftPadding) + field + ' '.repeat(totalPadding - leftPadding);
  // Map through each row and align fields, then join them into a string
  const alignedRows = => {
    return, idx) => alignField(field, colWidths[idx], alignment)).join(' ');
  // Join all aligned rows with newline characters
  return alignedRows.join('\n');
// Sample text for testing
const testText = [
// Displaying aligned text for different alignments
console.log("Right Aligned:\n" + formatText(testText, 'right'));
console.log("\nLeft Aligned:\n" + formatText(testText, 'left'));
console.log("\nCenter Aligned:\n" + formatText(testText, 'center'));

This solution uses the padStart and padEnd methods for left and right alignment, and a combination of both for central alignment. It ensures that the number of columns is normalized across all lines and calculates the maximum width of each column to determine the necessary spacing.

I hope this helps anyone facing this challenge. Feel free to give it a try and share your feedback or your own solutions!

We don’t allow solution code to be posted.

I have blurred it, but unless a thread invites a discussion or asks a question, we usually delete the code.