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");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
