Start learning free

LESSON 22 OF 68 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in JavaScript: Descending Order with sort() and reverse()

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), 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: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Sort ascending first, then call .reverse(). Or pass a comparator. Either way, copy the array first to avoid mutating the input.

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

STEP 1 OF 2
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in JavaScript, explained

    Problem overview

    The second version of the sort tool adds the reverse flag. The method sortLines(lines) receives an array of strings and returns them in descending order by character code, joined by \n. Duplicates are kept and an empty array gives "".

    Descending is the exact opposite of the ascending order of the previous version. Lowercase letters now come before uppercase ones, because lowercase letters have larger character codes, and an empty line comes last.

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

    Approach: ascending first, then turn it around

    The default sort() already orders strings ascending by character code. Reversing an ascending list gives the descending list, so the new work is a single extra call: reverse().

    As in the first version, the copy matters. Both sort() and reverse() change the array they are called on, and both return that same array. Starting from a spread copy, [...lines], keeps the caller's array untouched, and the two calls can then be chained on the copy.

    Step by step

    1. Build the sorted copy. Spread lines into a new array, call sort() on it and then reverse(), and store the result in the constant sortedLines. Sorted from smallest to biggest and then reversed, it runs from biggest to smallest.
    2. Join and return. join("\n") puts a newline between each two lines and none after the last, so an empty array gives "".

    The solution in JavaScript

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

    What to notice:

    • Method chaining works because both methods return the array. [...lines].sort() is the sorted copy, and .reverse() reverses that same array in place and returns it.
    • Both calls change the array. Neither makes a new one, so without the spread the caller's array would end up sorted and then reversed.
    • Another way to write it. A comparator that answers the opposite of the default, such as (a, b) => (a < b ? 1 : a > b ? -1 : 0), sorts descending in one pass. The lesson uses reverse() because it is shorter and obviously correct.
    • Equal lines look the same either way. Duplicates are identical strings, so their order relative to each other cannot be seen in the output.

    Complexity

    Time: O(n log n) for the sort of n lines, plus O(n) for the reversal and the join. The sort dominates.

    Space: O(n) for the copy and the output string. The reversal is done in place.

    Edge cases and common mistakes

    • Empty array. [] returns "".
    • Empty line. ["apple", "Zebra", "", "banana", "apple"] gives "banana\napple\napple\nZebra\n". The empty line is last, so the text ends with a newline that comes from joining the last real line with the empty one.
    • Reversing before sorting. [...lines].reverse().sort() just sorts ascending, because sort() overwrites whatever order the reverse produced.
    • Forgetting the copy. The returned text is right, but the caller's array has been reordered.
    • Reading the result as a new array. reverse() returns the same array it changed, so a.reverse() === a is true. Copy first if you need the original order too.

    Testing

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