Start learning free

LESSON 4 OF 68 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in JavaScript: Concatenate Files with Nested Loops

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

concatCat(allLines)

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Two steps: flatten the array of arrays into one flat array, preserving order. Then join with "\n".

You can use the built-in allLines.flat(), or do nested loops by hand:
for (let i = 0; i < allLines.length; i++) {
    for (let j = 0; j < allLines[i].length; j++) {
        flat.push(allLines[i][j]);
    }
}


The full solution:
class Solution {
    concatCat(allLines) {
        let flat = [];
        for (let i = 0; i < allLines.length; i++) {
            for (let j = 0; j < allLines[i].length; j++) {
                flat.push(allLines[i][j]);
            }
        }
        return flat.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in JavaScript, explained

    Problem overview

    The real cat takes several files and prints them one after another. This version models that with concatCat(allLines). The argument is an array of "files", and each file is itself an array of lines. The method flattens all the lines in order and joins them with newlines.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty and add no lines, and with no files at all the result is an empty string.

    Approach: flatten first, join once

    Collecting all the lines into one flat array makes the rest trivial, because that array can be joined exactly as in the first version. The flattening takes a loop inside a loop. The outer loop visits each file, and the inner loop visits each line of that file and pushes it onto the flat array. Files are read in order and lines in order inside each file, so the order of the output follows the input.

    Joining once at the end, rather than once per file, matters. Joining each file and then joining those results would also work, but an empty file would then produce an empty piece, and an extra blank row would show up between files.

    To see the difference, compare the two orders on [["a"], [], ["b"]]. Flattening first and joining once gives "a\nb". Joining each file separately and then joining those results gives "a\n\nb", with a blank row where the empty file was.

    Step by step

    1. Create an empty array named flat. It will hold every line of every file, with no arrays inside it.
    2. Loop over the files with i. Here allLines[i] is one file, an array of lines.
    3. Loop over that file's lines with j, inside the first loop, up to allLines[i].length.
    4. Push allLines[i][j] onto flat. An empty file never enters the inner loop, so it adds nothing.
    5. Return flat.join("\n") after both loops, so it runs once.

    The solution in JavaScript

    class Solution {
        concatCat(allLines) {
            let flat = [];
            for (let i = 0; i < allLines.length; i++) {
                for (let j = 0; j < allLines[i].length; j++) {
                    flat.push(allLines[i][j]);
                }
            }
            return flat.join("\n");
        }
    }

    Language details

    • The two indexes are separate: i picks the file and j picks the line, which is why the line is allLines[i][j].
    • The inner bound is allLines[i].length, the length of the current file, not of the whole list.
    • The built-in flat() method does the same flattening in one call: [["a"], [], ["b", "c"]].flat().join("\n") gives "a\nb\nc". The lesson writes the loops out so the process is visible.

    Testing

    The method returns these results:

    [["a"],[],["b","c"]] -> "a\nb\nc"
    [[],[]] -> ""
    [] -> ""

    Edge cases and common mistakes

    • Empty files. The empty array between ["a"] and ["b", "c"] contributes nothing, and no blank row appears.
    • No files. The outer loop never runs, flat stays empty, and join returns "".
    • Mixing up the indexes. Writing allLines[j][i] reads the wrong element or throws when a file is shorter.
    • Returning inside a loop. The return belongs after both loops, otherwise the method stops after the first line.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free