June 4, 2012

how to get the unique items in jquery

Question by vipin katiyar

I have the html file like below:

<div id="ultreecurri" style="float:left;">
<ul>

<li id="li1" class="popupul" style="text-align: left;">International</li>
<li id="li10" class="popupul" style="text-align: left;">Science</li>
<li id="li332" class="popupul" style="text-align: left;">Physics</li>
<li id="li2" class="popupul" style="text-align: left;">Africa</li>
<li id="li3" class="popupul" style="text-align: left;">Asia</li>
<li id="li5" class="popupul" style="text-align: left;">Caribbean</li>
<li id="li8" class="popupul" style="text-align: left;">North America</li>
<li id="li9" class="popupul" style="text-align: left;">South America</li>
<li id="li1" class="popupul" style="text-align: left;">International</li>
<li id="li10" class="popupul" style="text-align: left;"> Science</li>
<li id="li332" class="popupul" style="text-align: left;">Physics</li>
<li id="li2" class="popupul" style="text-align: left;">Africa</li>
<li id="li3" class="popupul" style="text-align: left;">Asia</li>
<li id="li5" class="popupul" style="text-align: left;">Caribbean</li>
<li id="li8" class="popupul" style="text-align: left;">North America</li>
<li id="li9" class="popupul" style="text-align: left;">South America</li>
 </ul>
</div>

how can i get the unique text of li items according to their liids.

Answer by Starx

The markup contains so many duplicated ID so, it is not a valid Markup. Instead I suggest you to remove the duplicate element, thus having a unique element on an array.

Here is a snippet for this purpose.

var list = {};
$('li').each(function() {
    var id = $(this).attr('id');
    if (list[id])
        $(this).remove();
    else
        list[id] = $(this);
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!