Jeroen Jeroen - 1 year ago 55
Javascript Question

Find duplicates by class and remove

<ul class="list">
<li class="item_20"></li>
<li class="item_20"></li>
<li class="item_20"></li>
<li class="item_21"></li>
<li class="item_21"></li>
<li class="item_22"></li>
<li class="item_22"></li>
</ul>


Is there a way with jQuery to determine and remove duplicates BY class in the example above? So only one li remains of every unique class.

Answer Source

This code below should work for your problem

var elem = {};
$('ul.list li').each(function() {
   var txt = $(this).attr('class');
   if (elem[txt])
       $(this).remove();
   else
       elem[txt] = true;
});

You can find out the explanations here : http://stackoverflow.com/a/2822974/4673732

Here's a fiddle with a demo : JSfiddle