Start learning free

LESSON 619 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in JavaScript: Ascending Sort by Character Code

Practice Read the full explanation

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

sortLines(lines)

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

JavaScript's Array.prototype.sort mutates the array in place. To avoid touching the input, copy first with [...lines], then sort.

The full solution:
class Solution {
    sortLines(lines) {
        const sortedLines = [...lines].sort();
        return sortedLines.join("\n");
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in JavaScript, explained

    Problem overview

    This is the first version of a small sort command. The method sortLines(lines) receives an array of strings and returns them in ascending order, joined by \n into one string. Duplicates are kept, and an empty array gives an empty string.

    The order is by character code, not by dictionary rules. Every character has a numeric code, and strings are compared character by character using those numbers. All uppercase letters have smaller codes than all lowercase letters, so "Zebra" comes before "apple". An empty string is smaller than any other string, so an empty line comes first.

    For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry".

    Approach: sort a copy, then join

    JavaScript already has what is needed. When Array.prototype.sort() gets no comparator, it converts the elements to strings and compares them by their UTF-16 code units, which for ordinary text means by character code. That is exactly the order the task asks for.

    There is one catch. sort() reorders the array it is called on and returns that same array. A function that sorts its parameter directly would reorder the caller's array as a side effect. The lesson avoids this by copying first.

    Step by step

    1. Copy and sort. Spread the input into a new array with [...lines], call sort() on the copy and store the result in the constant sortedLines. The copy is the array that gets reordered, so lines stays as it was.
    2. Join and return. join("\n") glues the elements together with a newline between each pair. The separator goes only between elements, so there is no newline after the last line, and an empty array produces "".

    The solution in JavaScript

    class Solution {
        sortLines(lines) {
            const sortedLines = [...lines].sort();
            return sortedLines.join("\n");
        }
    }
    

    Some details of this code:

    • Why the copy is needed. Arrays are passed by reference, so both the caller and the method see the same array. With const orig = ["b", "a"], calling orig.sort() turns orig into ["a", "b"]. With the spread copy, orig remains ["b", "a"].
    • The default order is textual. For numbers it gives surprising results: [10, 9, 1].sort() is [1, 10, 9], because "10" is compared with "9" as text. That is harmless here, since every element is a string, but it matters in the next kinds of sort.
    • const does not freeze the array. It only stops sortedLines from being reassigned. The array behind it can still change, which is why the copy matters.

    Complexity

    Time: O(n log n) comparisons for n lines, from the sort. Each comparison looks at the strings' characters, so the real cost also grows with line length. Copying and joining are linear in the total size of the text.

    Space: O(n) for the copy of the array, plus the output string.

    Edge cases and common mistakes

    • Empty array. [] returns "".
    • Empty line. ["apple", "Zebra", "", "banana", "apple"] gives "\nZebra\napple\napple\nbanana": the empty line first, then "Zebra", then the lowercase words, with both "apple"s kept.
    • Sorting the input directly. lines.sort().join("\n") returns the right text but reorders the caller's array.
    • Expecting dictionary order. The default sort does not ignore case. If you wanted "apple" before "Zebra", you would need a comparator such as localeCompare, which is a different order from the one asked for here.
    • Joining with a trailing newline. Adding "\n" after the last line would make the output differ from the expected text.

    Testing

    • ["banana", "apple", "cherry"] gives "apple\nbanana\ncherry".
    • ["apple", "Zebra", "", "banana", "apple"] gives "\nZebra\napple\napple\nbanana".
    • [] gives "".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free