3

I use this code:

window.removeDuplicateLines = function() {
"use strict";
    var bodyText = $('#text-area').val().split('\n');
    var uniqueText = [];
    $.each(bodyText, function(i, el){
        if($.inArray(el, uniqueText) === -1) {
            uniqueText.push(el);
        }
    });

    document.getElementById('text-area').value = uniqueText.join('\n');
};

from here: Remove Duplicates from JavaScript Array to remove duplicate lines from the textarea.

This code works good, but it removes empty lines also as duplicates.

Question: How can I remove duplicate lines, but keep (ignore) empty lines, with this code?

Community
  • 1
  • 1
Mik Abe
  • 97
  • 1
  • 9

1 Answers1

2

You need to see if the entire line has just spaces. To do so you can trim() and then check if length is 0. So change your if check to below

   if($.inArray(el, uniqueText) === -1 || $.trim(el).length === 0) {
        uniqueText.push(el);
    }
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59