Start learning free

LESSON 392 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v4 — Sort by Key Column in JavaScript

Practice

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

sortLines(lines, field)

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Pass a comparator that splits each operand on "," and compares the field - 1 elements with < and > (return -1, 1 or 0; not localeCompare, which orders by locale). Modern V8's Array.prototype.sort is stable.

The full solution:
class Solution {
    sortLines(lines, field) {
        const sortedLines = [...lines].sort((a, b) => {
            const x = a.split(",")[field - 1];
            const y = b.split(",")[field - 1];
            return x < y ? -1 : x > y ? 1 : 0;
        });
        return sortedLines.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    Sort V4 in JavaScript

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free