-2

I'm trying to remove duplicate lines in a div

<div id="content>
  <p>Hello</p>
  <p>why</p>
  <p>are</p>
  <p>hello</p>
</div>

The output is shown as

hello
why
are
hello

How can I remove the duplicate lines?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
sravya naidu
  • 39
  • 1
  • 8
  • There are far too many solutions to this questions. show us what `jquery` code you have tried so we can narrow it down. – Daniel_ZA Mar 08 '17 at 11:15
  • I found for the duplicates in array but not in div – sravya naidu Mar 08 '17 at 11:16
  • 1
    you should explain us a bit more about your code. Where are these data coming from? How do you populate the div with data? If this is coming from some server side input (db) why don't you sanitize the input then? When this "removal" should happen? On user request? – Lelio Faieta Mar 08 '17 at 11:16
  • if you have an array and you find duplicates there, just remove them from the array before using it! – Lelio Faieta Mar 08 '17 at 11:17
  • @Daniel_ZA why Jquery? You can do it also with plain javascript or server side. – Lelio Faieta Mar 08 '17 at 11:18
  • @LelioFaieta just thought I would point out Jquery since the title of the question was "javascript jquery" – Daniel_ZA Mar 08 '17 at 11:23

3 Answers3

1

If you are concerned about case, just remove the .toLowerCase()

var seen = {};
$('#content>p').each(function() {
  var txt = $(this).text().toLowerCase();
  if (seen[txt])
    $(this).remove();
  else
    seen[txt] = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="content">
  <p>Hello</p>
  <p>why</p>
  <p>are</p>
  <p>hello</p>
</div>
Brad
  • 8,044
  • 10
  • 39
  • 50
0

use an object as map

var map = {};
$('p').each(function(){
    var value = $(this).text();
    if (map[value] == null){
        map[value] = true;
    } else {
        $(this).remove();
    }
});
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Athul
  • 801
  • 7
  • 16
0

Duplicate lines? Could you please post a screenshot of how it looks? Do you want the wording spaced closer to each other in the paragraph tags? If this is the case, try using CSS

#content {
    line-height: 0.5;
}

Also, you missed a " in id="content"