Start learning free

LESSON 15 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -v in JavaScript: Invert Match with !includes()

Practice Read the full explanation

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

grepInvert(lines, pattern)

Example:

Input:
pattern = "err"
lines = ["error", "ok", "another error", "fine"]

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep lines where !line.includes(pattern).

The full solution:
class Solution {
    grepInvert(lines, pattern) {
        let result = [];
        for (let i = 0; i < lines.length; i++) {
            if (!lines[i].includes(pattern)) {
                result.push(lines[i]);
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in JavaScript, explained

    Problem overview

    The method grepInvert(lines, pattern) is the -v flag of the Unix grep command: it returns the lines that do not contain the pattern. The match is case-sensitive, the surviving lines keep their original order, and they are joined with "\n". If every line contains the pattern, the result is the empty string.

    With pattern = "err" and lines = ["error", "ok", "another error", "fine"], the first and third lines contain err and are dropped. What remains is "ok" and "fine", so the result is "ok\nfine".

    Approach: the same loop with the test flipped

    Version 1 kept a line when includes was true. This version keeps it when includes is false. Everything else, the empty result array, the loop, the push and the final join, stays identical. A single ! in front of the condition is the whole change.

    That small difference is the point of the lesson: real tools are often one idea plus a flag that reverses it. You write the core once and flip the condition, instead of writing a second algorithm.

    Because the loop visits lines from first to last and pushes survivors in that order, the original order is preserved with no extra work.

    Tracing the example: "error" contains err, so the test is false and it is skipped; "ok" does not, so it is pushed; "another error" is skipped; "fine" is pushed. The array ends up as ["ok", "fine"], and join("\n") turns it into "ok\nfine".

    Notice what is not needed: no second array for the dropped lines, and no copying or sorting. A filter only has to decide, line by line, keep or drop.

    Step by step

    1. Create result as an empty array. It will hold the lines that do not contain the pattern.
    2. Loop over the positions with for (let i = 0; i < lines.length; i++).
    3. Test with a negation: if (!lines[i].includes(pattern)). The ! operator turns true into false and the other way round, so the body runs for lines without the pattern.
    4. Push lines[i] onto result. Only lines without the pattern reach this line.
    5. Return result.join("\n") after the loop.

    The solution in JavaScript

    class Solution {
        grepInvert(lines, pattern) {
            let result = [];
            for (let i = 0; i < lines.length; i++) {
                if (!lines[i].includes(pattern)) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }
    

    Details worth knowing:

    • ! binds tighter than most operators, but here it applies to the whole call: !lines[i].includes(pattern) evaluates lines[i].includes(pattern) first and then negates the boolean result. No extra parentheses are needed.
    • includes is case-sensitive, so "Error" does not contain "err" and is kept: ["Error", "x"] gives "Error\nx".
    • An empty lines array gives "", because the loop never runs and an empty array joins to the empty string.

    Complexity

    Every line is searched once, so the time is bounded by the total text size times the pattern length, the same as the plain match. The result array holds at most one reference per line.

    Edge cases and common mistakes

    • Forgetting the !. The function then returns the matching lines, which is version 1's answer.
    • Everything matches. With ["error", "another error"] and "err" the result is "".
    • Empty input. An empty array gives "".
    • Case. Lines that differ only in capitals from the pattern do not contain it, so they are kept.

    Testing

    linespatternresult
    ["error", "ok", "another error", "fine"]"err""ok\nfine"
    ["error", "another error"]"err"""
    ["Error", "x"]"err""Error\nx"
    []"err"""
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free