Start learning free

LESSON 390 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v2 — Reverse (Descending) Sort in JavaScript

Practice

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

    Sort V2 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