dave
dave

Reputation: 1679

jquery remove duplicate li

<ul id="myid">   
<li>microsoft</li>  
<li>microsoft</li>  
<li>apple</li>  
<li>apple</li>  
</ul>   

I want to remove duplicates from li by using jquery.

How can I do that?

Upvotes: 11

Views: 16571

Answers (5)

eduardomozart
eduardomozart

Reputation: 1454

I have used @Thariama solution in the past, but I have compatibility problems with IE6 (I still needs to support this dinosaur).

If the item repeats, so remove it from ul. It works with dynamic added li.

            var seen = {};
            $("ul#emails_exclusion_list").find("li").each(function(index, html_obj) {
                txt = $(this).text().toLowerCase();

                if(seen[txt]) {
                    $(this).remove();
                } else {
                    seen[txt] = true;
                }
            });

Upvotes: 1

Mark Bell
Mark Bell

Reputation: 29735

Here's a function that will do it, a slightly different way:

function removeDuplicateItems(id) {
    var ul = $('#' + id);

    $('li', ul).each(function() {
        if($('li:contains("' + $(this).text() + '")', ul).length > 1)
            $(this).remove();
    });
}

Call with removeDuplicateItems('myid');

Upvotes: 3

andres descalzo
andres descalzo

Reputation: 14967

example I find that the script is faster

var liText = '', liList = $('#myid li'), listForRemove = [];

$(liList).each(function () {

  var text = $(this).text();

  if (liText.indexOf('|'+ text + '|') == -1)
    liText += '|'+ text + '|';
  else
    listForRemove.push($(this));

})​;

$(listForRemove).each(function () { $(this).remove(); });

Upvotes: 8

Thariama
Thariama

Reputation: 50832

You could use

var inner = [];
$('li').each( function(index, Element){
    if (jQuery.inArray(this.innerHTML, inner) == -1){
      inner.push(this.innerHTML);
    }
    else {
      $(this).remove();
    }
});

Upvotes: 6

Tomalak
Tomalak

Reputation: 338158

uniqueLi = {};

$("#myid li").each(function () {
  var thisVal = $(this).text();

  if ( !(thisVal in uniqueLi) ) {
    uniqueLi[thisVal] = "";
  } else {
    $(this).remove();
  }
})

This build an index (an object) of unique values. For your example, uniqueLi will look like this afterwards:

{
  "microsoft": "", 
  "apple": ""
}

So whenever a value is encountered that has been added to the index before, the associated <li> gets removed.

Upvotes: 7

Related Questions