Start learning free

LESSON 24 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in TypeScript: Stable Sort by Key Column

Practice Read the full explanation

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: string[], field: number): string

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: string[], field: number): string {
        const sortedLines: string[] = [...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

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in TypeScript, explained

    Problem overview

    The fourth version of the sort project adds the effect of the -k flag. Each line is comma-separated, and every line has at least field fields. A field may be empty, as in "a,,c". The method sortLines(lines: string[], field: number) sorts the lines by the value in the 1-indexed column field, comparing the values as strings by character code. It returns the original lines joined by \n. Lines whose keys are equal keep their input order, and an empty array gives "".

    For field = 2 and ["alice,30", "bob,25", "carol,40"], the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40".

    Approach: a comparator that extracts the key

    Sorting whole lines would order them by their first column. To order by another column, sort() needs a comparator that looks only at the key. For two lines a and b, split each at the commas and take the piece at position field - 1: fields count from 1, positions count from 0. Then compare the two keys.

    The comparison must return a negative number, a positive number or zero. The keys are strings, so subtraction is not available. The lesson uses the relational operators, which compare strings by code unit: x < y gives -1, x > y gives 1 and anything else, meaning equal keys, gives 0.

    Returning 0 for equal keys is what makes ties keep their input order. Array sorting in modern JavaScript is stable, so two lines that compare as equal are not swapped. The lines "b,1" and "a,1" compared on field 2 stay in the order they came in, even though "a,1" would come first as a whole line.

    The key is computed again on every comparison. That keeps the code short, and for line-sized input it is fine.

    Step by step

    1. Start the sort. Create const sortedLines: string[] from [...lines].sort(...), passing an arrow function of a and b. The spread copies the array so the caller's array is untouched. Write the closing }); right away.
    2. Get the key of a: const x = a.split(",")[field - 1].
    3. Get the key of b the same way, as y.
    4. Return the comparison: -1 when x is smaller, 1 when it is bigger, 0 otherwise, using two chained ? : operators.
    5. Join the sorted lines with "\n" and return the text.

    The solution in TypeScript

    class Solution {
        sortLines(lines: string[], field: number): string {
            const sortedLines: string[] = [...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");
        }
    }
    

    Language details

    • split(",") keeps empty pieces: "a,,c".split(",") is ["a", "", "c"], so an empty field is a valid key, an empty string that sorts before everything else.
    • The chained ? : reads from left to right: if x < y then -1, otherwise if x > y then 1, otherwise 0.
    • Comparing the keys as strings means "10" is smaller than "9", because "1" comes before "9". That is what this version asks for.
    • The arrow function has a block body with braces, so it needs an explicit return.

    Complexity

    With n lines, the sort does O(n log n) comparisons. Each one splits two lines, costing time proportional to their lengths, so the total is O(n log n) comparisons times the line length. The copy and the output take O(n) extra space, plus the temporary arrays made by split.

    Edge cases and common mistakes

    • Off-by-one on the column. Using field instead of field - 1 reads the wrong column, or undefined past the last one.
    • Returning only -1 or 1. Without the zero case, equal keys are reported as "greater", so the result no longer reliably keeps ties in input order.
    • Ties. With field = 2, ["b,1", "a,1", "c,0"] gives "c,0\nb,1\na,1": "b,1" stays ahead of "a,1".
    • Text order of numbers. With field = 2, ["x,10", "y,9"] stays as it is, because "10" is smaller than "9" as text.
    • Empty fields. With field = 2, ["a,,c", "b,a,c"] gives "a,,c\nb,a,c": the empty key goes first.
    • Empty input. [] gives "".

    Testing

    InputResult
    field = 2, ["alice,30", "bob,25", "carol,40"]"bob,25\nalice,30\ncarol,40"
    field = 1, ["alice,30", "bob,25", "carol,40"]"alice,30\nbob,25\ncarol,40"
    field = 2, ["b,1", "a,1", "c,0"]"c,0\nb,1\na,1"
    field = 2, ["x,10", "y,9"]"x,10\ny,9"
    field = 2, ["a,,c", "b,a,c"]"a,,c\nb,a,c"
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free