Start learning free

LESSON 622 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in JavaScript: Stable Sort by a 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, 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

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in JavaScript, explained

    Problem overview

    This version of the sort tool sorts by one column, like the -k flag. The method sortLines(lines, field) receives comma-separated lines and a 1-indexed field number. Every line has at least that many fields, and a field may be empty, as in "a,,c".

    The method sorts the lines by the value in that field, comparing the values as strings by character code, and returns the original lines joined by \n. Lines whose keys are equal keep their input order, so the sort must be stable. 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: extract the key inside the comparator

    The sort needs a comparator, because the order depends on a part of each line rather than the whole line. For two lines a and b, the comparator splits each one at the commas, takes the piece at position field - 1 (fields count from 1, array positions from 0) and compares the two pieces.

    The comparator returns -1 when the first key is smaller, 1 when it is bigger and 0 when the keys are equal. Plain < and > on two strings compare by UTF-16 code unit, which for ordinary text is the character code the task asks for.

    Returning 0 for equal keys is what keeps ties in input order. Array.prototype.sort has been required to be stable since ES2019, so Node 22 leaves tied elements in their original order, and no extra tie-breaker is needed.

    Step by step

    1. Start the sorted copy. Spread lines into a new array and call sort with an arrow function of a and b. The copy keeps the caller's array unchanged.
    2. Get the key of a: a.split(",")[field - 1], stored in x.
    3. Get the key of b the same way, stored in y.
    4. Return the comparison with two chained ? : operators: -1 if x < y, otherwise 1 if x > y, otherwise 0.
    5. Join and return the sorted lines with join("\n"). The separator goes only between lines.

    The solution in JavaScript

    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");
        }
    }
    

    Some details of this code:

    • split keeps empty fields. "a,,c".split(",") is ["a", "", "c"], so field 2 is the empty string, which sorts before every non-empty key.
    • The output keeps whole lines. The key is used only for comparing. The array being sorted still contains the original strings.
    • Chained conditional operators. x < y ? -1 : x > y ? 1 : 0 groups from the right: if the first test fails, the second ? : decides between 1 and 0.
    • Why not x - y. The keys are strings, and subtracting two non-numeric strings gives NaN. Comparison operators work on strings directly.
    • The key is computed on every comparison. Each line is split many times during the sort. That is simple and fast enough here, and a faster variant would split every line once beforehand.

    Complexity

    Let n be the number of lines and L the length of a line.

    Time: O(n log n) comparisons, each splitting two lines, so about O(n log n * L) overall. The final join is linear in the total text.

    Space: O(n) for the copy of the array and the output, plus the temporary arrays that split makes, which are discarded after each comparison.

    Edge cases and common mistakes

    • Ties keep input order. For field = 2 and ["x,b", "y,a", "z,b", "w,a"] the result is "y,a\nw,a\nx,b\nz,b": "y,a" stays ahead of "w,a", and "x,b" stays ahead of "z,b".
    • Empty keys. With field = 2, ["a,,c", "b,x,d", "c,,e"] gives "a,,c\nc,,e\nb,x,d". The two empty keys come first, in their input order.
    • Off-by-one on the field. Field 1 is position 0. Using field as the index would pick the wrong column, or undefined past the end.
    • Keys compare as text. For field = 2 and ["b,10", "a,9"] the result is "b,10\na,9", because "10" is smaller than "9" as text. Numbers in a column are not sorted numerically.
    • Uppercase before lowercase. For field = 1 and ["Bob,1", "alice,2"], "Bob" comes first, since uppercase letters have smaller character codes.
    • Comparing the whole lines. That orders by the line's first characters, not by the chosen field, and it breaks ties by the rest of the text instead of keeping input order.
    • Empty array. It returns "".

    Testing

    • field = 2, ["alice,30", "bob,25", "carol,40"] gives "bob,25\nalice,30\ncarol,40".
    • field = 1, the same lines, gives "alice,30\nbob,25\ncarol,40".
    • field = 2, ["x,b", "y,a", "z,b", "w,a"] gives "y,a\nw,a\nx,b\nz,b".
    • field = 2, ["a,,c", "b,x,d", "c,,e"] gives "a,,c\nc,,e\nb,x,d".
    • field = 1, ["b,10", "a,9"] gives "a,9\nb,10".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free