views:

80

answers:

4
<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?

+3  A: 
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.

Tomalak
+4  A: 

You could use

var inner = [];
$('li').each( function(index, Element){
    if (jQuery.inArray(this.innerHTML, inner) == -1){
      inner.push(this.innerHTML);
    }
    else {
      $(this).remove();
    }
});
Thariama
`jQuery.inArray()` is kinda inefficient when compared to the `in` operator for objects.
Tomalak
+1  A: 

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');

Mark B
This will fail when the item text contains a single quote. ;-)
Tomalak
I can see why you'd say that, but actually it doesn't—something (either the `contains` selector or the `.text()` function, I can't figure out which from the jQuery source) auto-escapes the quotes. Take a look: http://jsfiddle.net/kXurk/
Mark B
Hi Mark, thanks for the code. but how can we do it "Live" ?
dave
Not sure what you mean by “Live”, Dave—if you mean that you are adding more elements to the list client-side and want to de-dupe them as well, just call this function every time you add new elements. Otherwise, please give a bit more explanation (or set up a new question).
Mark B
+2  A: 

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(); });
andres descalzo
Thanks andres descalzo, How Can we do it with "LIVE" data ??
dave
could you give an example with what you do, or another question with the problem?
andres descalzo