satriabajakan satriabajakan - 5 days ago 5
Javascript Question

JavaScript Remove Duplicate Tags on Div element

How do I delete the same text on the tag element?
In this case I have found this trick:



var seen = '';

$('div').each(function() {
var see = $(this).text();
if (seen.match(see)) {
$(this).remove();
} else {
seen = $(this).text();
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Book</div>
<div>Book</div>
<div>Book</div>
<div>Pencil</div>
<div>Pencil</div>
<div>Book Book Book Pencil Pencil</div>





The above code is not wrong. Because I have the same few words wrapped in the same tag.

<div>Book Book Book Pencil Pencil</div>


Is there a way around this problem?

Edit: I want to change into
<div>Book Pencil</div>

Answer

I have given a nice solution below.

Note: The following two examples work well with the same script as you expected. It's a generic script and will work for both examples

Example 1

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Book</div>
<div>Book</div>
<div>Book</div>
<div>Pencil</div>
<div>Pencil</div>
<div>Book</div>
<div>Book Book Book Pencil Pencil</div>


<script>
var tags = [];
   $('div').each(function(){
       var tagArray = $(this).text().split(' ');
     
       for(var i = tagArray.length - 1; i >= 0; i--) {
          var tag = tagArray[i];
          if(tags.indexOf(tag) > -1) {
             tagArray.splice(i, 1);
          } else {
            tags.push(tag);
          }
       }
     
       var currentTag = tagArray.join(' ');
     
        if(currentTag){
            $(this).text(currentTag);
        }
        else{
            $(this).remove();
        }
    });
</script>

Example 2

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Book Book Book Pencil Pencil</div>


<script>
var tags = [];
   $('div').each(function(){
       var tagArray = $(this).text().split(' ');
     
       for(var i = tagArray.length - 1; i >= 0; i--) {
          var tag = tagArray[i];
          if(tags.indexOf(tag) > -1) {
             tagArray.splice(i, 1);
          } else {
            tags.push(tag);
          }
       }
     
       var currentTag = tagArray.join(' ');
     
        if(currentTag){
            $(this).text(currentTag);
        }
        else{
            $(this).remove();
        }
    });
</script>

Comments