日本語

Removing Duplicate Lines from Pasted Text in React

​​React​JavaScript,Playwright,TypeScript,Unicode

The shortest way to remove duplicate lines is to split the text into lines, put them in a Set, and convert the result back to an array. This keeps the order of first appearance and drops the second and later occurrences. However, when lists are copied from other places, lines that look identical can remain as separate lines because of trailing spaces or differences between full-width and half-width characters. So I normalized only the strings used for comparison, and kept the first occurrence of each line as the one that remains.

Here I built LineDeduper, a React component that removes duplicate lines from pasted text. Four comparison options can each be turned on or off: "ignore leading and trailing spaces," "do not distinguish uppercase and lowercase," "do not distinguish full-width and half-width," and "remove empty lines." The result can be copied with a button.

Note

Test environment: Ubuntu 24.04, Node.js 22.23.4, Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I checked the results of the functions in Node.js and checked that the component has no type errors with tsc. Then I ran a development build wrapped in StrictMode in Chromium at a 375px width and operated it from Playwright. For pasting, I put a string into the clipboard with Playwright and then pressed Ctrl+V. I did not test Firefox, Safari, real smartphones, or speed in a production build.

Component at a 375px width. The labels in this image are in Japanese, so their meaning is given here. The input contains "apple," "mandarin," "Apple," "grape," "mandarin" again, an empty line, "apple," and "APPLE" in full-width letters. All four checkboxes are on. Under "11 lines → 5 lines (6 lines removed)," the result box shows five lines: apple, mandarin, Apple, grape, and "banana" in half-width katakana. The button reads "Copied," and below it, under "Lines that appeared 2 or more times (4 kinds)," entries such as "Apple … 3 times" are listed.
Eleven lines pasted, all four comparison options turned on, and the result copied

Lists That new Set Removes and Lists That Remain

The shortest approach is to split the text by newlines, put the lines into a Set, and convert it back to an array. A Set holds only one copy of each value and returns the values in insertion order.

ts
const unique = [...new Set(text.split('\n'))];

When I passed 'りんご\nみかん\nりんご\nぶどう\nみかん' to this code in Node.js, I got ["りんご","みかん","ぶどう"]. Only the second occurrences of the apple and mandarin lines were removed, and the order stayed the same as the first appearance.

However, a Set treats strings as different values if even one character differs. I tried the same code on lists that contain lines that look the same but are different strings.

List Result of new Set
Line endings are mixed: some lines end in \r\n and some in \n "りんご\r" and "りんご" both remain
A half-width space at the end "りんご" and "りんご " both remain
A full-width space at the start "りんご" and " りんご" both remain
Uppercase and lowercase "Apple", "apple", and "APPLE" all remain
Full-width and half-width letters and digits "ABC123" and "ABC123" both remain
Half-width katakana "カタカナ" and "カタカナ" both remain
Several empty lines One empty string "" remains

Whether uppercase and lowercase should count as the same line, and how far "the same line" should reach in general, depends on the content of the list. So in this component, the user can choose each of these options.

In Chromium, no \r remained in the textarea value after pasting

The \r in the first row of the table was not a problem in my Chromium environment when pasting into a <textarea>. I put an 11-line list separated by \r\n into the clipboard and pasted it with Ctrl+V. The string read with navigator.clipboard.readText() contained 11 \r characters. However, the value of the input after pasting contained no \r and had 11 \n characters.

The input value has only \n. The function splits lines on \r\n, \r, and \n alike, so it also works with strings from sources other than the input.

A function that normalizes strings only for comparison

I put the removal logic in dedupeLines.ts. dedupeLines() returns the lines kept, the lines that appeared two or more times along with their counts, and the original line count.

ts
// Function that removes duplicate lines from pasted text

export type DedupeOptions = {
  trim: boolean; // Compare ignoring leading and trailing spaces in each line
  ignoreCase: boolean; // Do not distinguish uppercase and lowercase letters
  normalizeWidth: boolean; // Ignore the difference between full-width and half-width (NFKC)
  dropEmpty: boolean; // Remove empty lines (including lines with only spaces)
};

export type DedupeResult = {
  lines: string[]; // Lines kept. The first occurrence is kept (when ignoring leading and trailing spaces, the spaces are removed from the kept line)
  duplicates: { line: string; count: number }[]; // Lines that appeared two or more times, and how many times
  total: number; // Original line count
};

// Split on \r\n (Windows), \r, or \n. An empty line after a trailing newline is not counted
export function splitLines(text: string): string[] {
  if (text === '') return [];
  const lines = text.split(/\r\n|\r|\n/);
  if (lines.at(-1) === '') lines.pop();
  return lines;
}

// The string used for comparison. Full-width/half-width and letter case are normalized only here
function toKey(line: string, options: DedupeOptions): string {
  let key = line;
  if (options.normalizeWidth) key = key.normalize('NFKC');
  if (options.ignoreCase) key = key.toLowerCase();
  return key;
}

export function dedupeLines(text: string, options: DedupeOptions): DedupeResult {
  const all = splitLines(text);
  const seen = new Map<string, { line: string; count: number }>();
  const lines: string[] = [];
  for (const raw of all) {
    const line = options.trim ? raw.trim() : raw;
    if (options.dropEmpty && line.trim() === '') continue;
    const key = toKey(line, options);
    const found = seen.get(key);
    if (found) {
      found.count += 1;
      continue;
    }
    seen.set(key, { line, count: 1 });
    lines.push(line);
  }
  const duplicates = [...seen.values()].filter((v) => v.count > 1);
  return { lines, duplicates, total: all.length };
}

Keep the lines as they are and change only the strings compared

If I put the lines straight into a Set, the compared strings become the results. Even if I want to treat full-width and half-width as the same when comparing, I don't necessarily want the output converted to half-width. So I used a Map whose keys are the strings used for comparison and whose values hold the first line and its count. A Map also returns its keys in insertion order.

This is the result when all four options are on and I pass ' Apple\napple\nApple\nみかん\nみかん \n\nぶどう\nAPPLE'.

text
{"lines":["Apple","みかん","ぶどう"],"duplicates":[{"line":"Apple","count":4},{"line":"みかん","count":2}],"total":8}

The four "apple" entries that differ in letter case and width became one, and the line kept is the first one, "Apple." The full-width Apple and the all-uppercase APPLE were not kept as results. However, leading and trailing spaces are removed from the kept lines too, so the half-width space at the start of the first line does not remain in the result. If I kept the spaces, invisible trailing spaces would remain on the lines when the result is copied.

Methods used for the four comparison options

Leading and trailing spaces are removed with trim(). trim() removes full-width spaces (U+3000) as well as half-width spaces. For the list with a full-width space at the start in the table, turning on "ignore leading and trailing spaces" reduced it to one apple line.

Letter case is compared after converting to lowercase with toLowerCase().

Full-width and half-width characters are compared after normalizing with normalize('NFKC'). Full-width letters and digits become half-width, and half-width katakana become full-width. As a result, ABC123 and ABC123, and カタカナ and カタカナ, became the same lines. However, NFKC also changes characters other than full-width and half-width ones. I compared the following combinations in Node.js.

Combination Result of comparing with NFKC
① and 1 Same line
㈱ and (株) Same line
ガ (two half-width characters) and ガ Same line
- (U+FF0D) and - Same line
〜 (U+301C) and ~ (U+FF5E) Stay as different lines

If you want ① and 1 to remain as separate lines in a numbered list, turn off "do not distinguish full-width and half-width." How to convert between full-width and half-width while applying the conversion only to certain characters, such as half-width katakana, instead of changing too much with NFKC, is covered in detail in the article "How to Build a React Input for Converting Between Full-Width and Half-Width Characters."

Empty lines are the lines that become empty after trim(). When this option is off, one empty line is kept like any other line.

Adding an input and a button that copies the result

tsx
import { useId, useMemo, useState } from 'react';
import { dedupeLines, type DedupeOptions } from './dedupeLines';

const optionLabels: [keyof DedupeOptions, string][] = [
  ['trim', '前後の空白を無視する'],
  ['ignoreCase', '大文字と小文字を区別しない'],
  ['normalizeWidth', '全角と半角を区別しない'],
  ['dropEmpty', '空の行を取り除く'],
];

export function LineDeduper({ initial = '' }: { initial?: string }) {
  const id = useId();
  const [text, setText] = useState(initial);
  const [options, setOptions] = useState<DedupeOptions>({
    trim: true,
    ignoreCase: false,
    normalizeWidth: false,
    dropEmpty: true,
  });
  // The last copied string. Compare by content so that "Copied" disappears when the result changes
  const [copied, setCopied] = useState<string | null>(null);

  // With tens of thousands of pasted lines, avoid recounting every time another state changes
  const result = useMemo(() => dedupeLines(text, options), [text, options]);
  const output = result.lines.join('\n');
  const removedCount = result.total - result.lines.length;

  async function copy() {
    await navigator.clipboard.writeText(output);
    setCopied(output);
  }

  return (
    <div className="deduper">
      <label htmlFor={`${id}-input`}>一覧(1行に1つ)</label>
      <textarea id={`${id}-input`} rows={8} value={text} onChange={(e) => setText(e.target.value)} />
      <fieldset>
        <legend>比べ方</legend>
        {optionLabels.map(([key, label]) => (
          <label key={key}>
            <input
              type="checkbox"
              checked={options[key]}
              onChange={(e) => setOptions({ ...options, [key]: e.target.checked })}
            />
            {label}
          </label>
        ))}
      </fieldset>
      <p aria-live="polite">
        {result.total}行 → {result.lines.length}行({removedCount}行を取り除きました)
      </p>
      <label htmlFor={`${id}-output`}>重複を取り除いた一覧</label>
      <textarea id={`${id}-output`} rows={8} value={output} readOnly />
      <button type="button" onClick={copy} disabled={output === ''}>
        {copied === output ? 'コピーしました' : '結果をコピー'}
      </button>
      {result.duplicates.length > 0 && (
        <details>
          <summary>2回以上出てきた行({result.duplicates.length}種類)</summary>
          <ul>
            {result.duplicates.map((d) => (
              <li key={d.line}>
                <code>{d.line}</code> … {d.count}回
              </li>
            ))}
          </ul>
        </details>
      )}
    </div>
  );
}
css
.deduper {
  display: grid;
  gap: 8px;
  max-width: 560px;
}
.deduper textarea {
  font: inherit;
  white-space: pre;
  overflow-x: auto;
}
.deduper fieldset {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 16px;
  margin: 0;
}
.deduper button {
  justify-self: start;
}
.deduper ul {
  margin: 4px 0 0;
  padding-left: 1.5em;
}
.deduper code {
  white-space: pre;
  background: #eefafd;
}

The result is not held in state. It is computed on every render from the input string and the comparison options. However, after pasting tens of thousands of lines, a change such as the "Copied" label would otherwise recount everything, so I wrapped the computation in useMemo. useMemo returns the previous result as is if its dependencies (here text and options) have not changed.

The result is shown in a second <textarea> with readOnly. Even with tens of thousands of lines, it is a single element, and users can also select a range and copy it manually. For the button, I used navigator.clipboard.writeText(). The "Copied" label appears only when the copied string matches the current result. If a change to the comparison options changes the result, the button label goes back to "Copy result."

The sample in the screenshot is the following 11-line list. The second line, みかん, has a half-width space after it, and line 6 is empty.

text
りんご
みかん 
Apple
ぶどう
みかん

apple
APPLE
りんご
バナナ
バナナ

When I pasted this with Playwright and changed the comparison options one at a time, the number of lines changed as follows.

Comparison options Result
Initial state (ignore leading and trailing spaces, remove empty lines) 8 lines. The two mandarin lines are merged into one, and the empty line and the second apple line are removed
+ Do not distinguish uppercase and lowercase 7 lines. apple is merged into Apple
+ Do not distinguish full-width and half-width 5 lines. APPLE is merged into Apple, and the full-width and half-width banana lines are merged
From the state above, turn off "ignore leading and trailing spaces" 6 lines. The mandarin lines with and without a trailing space remain as separate lines

When full-width and half-width were matched, the half-width バナナ remained because it appeared first. Since only the strings used for comparison are normalized, which form remains depends on which line appeared first in the list.

When pasting a list with tens of thousands of lines

Another way to remove duplicates is to use filter() and indexOf() to keep only the lines whose first occurrence is at their own position. indexOf() searches the array from the beginning for each line. I made a list in which half of the lines are duplicates, using half-width alphanumerics such as item-123, and compared the shortest of three runs in Node.js.

Lines new Set filter() and indexOf() dedupeLines() (all four on)
1,000 lines 0.1ms 0.5ms 0.3ms
10,000 lines 0.8ms 44.1ms 2.8ms
100,000 lines 11.8ms 4,594.2ms 32ms

With 100,000 lines, the filter() and indexOf() approach took more than 4 seconds. dedupeLines() was slower than new Set, but it took 32 ms.

I also measured the time that operations took in the browser, using the same 100,000-line list. For pasting and typing, the time is measured until the line count display changes. For the checkbox, it is measured until the toggle finishes. I measured each operation once in a development build.

Operation Time taken
Paste 100,000 lines 2,686ms
After pasting, type one character at the end 1,523ms
Turn off one checkbox 983ms

On the same page, I measured only dedupeLines() three times, with the comparison options left as they were after turning off a checkbox, and got 35 to 61 ms. Comparing these numbers, most of the roughly 1.5 seconds it took to type one character was spent outside dedupeLines().

​Posted by 86