VafaK
VafaK

Reputation: 524

JQuery delete duplicates of an element

I have some labels on my form:

<label>8/22/2014</label> <!--label1-->
<label>8/22/2014</label> <!--label2-->
<label>8/23/2014</label> <!--label3-->
<label>8/24/2014</label> <!--label4-->
<label>8/25/2014</label> <!--label5-->
<label>8/25/2014</label> <!--label6-->
<label>8/26/2014</label> <!--label7-->
<label>8/26/2014</label> <!--label8-->
<label>8/26/2014</label> <!--label9-->

I want only first of each labels grouped by date to remain on the form and others be deleted. according to the example above, these elements should remain on the form:

<label>8/22/2014</label> <!--label1-->
<label>8/23/2014</label> <!--label3-->
<label>8/24/2014</label> <!--label4-->
<label>8/25/2014</label> <!--label5-->
<label>8/26/2014</label> <!--label7-->

how can I do this?

Upvotes: 1

Views: 47

Answers (3)

num8er
num8er

Reputation: 19372

$(function(){
    var dates = [];
    $('label').each(function(){
        if(dates.indexOf($(this).html())>-1) {
            $(this).remove();
            return;
        }

        dates.push($(this).html());
    });
});

or use jquery.unique : http://api.jquery.com/jquery.unique/

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

Try this:

var seen = {};
$('label').each(function() {
    var str = $(this).text();
    if (seen[str])
        $(this).remove();
    else
        seen[str] = true;
});

JSFIDDLE DEMO

Upvotes: 3

j08691
j08691

Reputation: 207891

$('label').each(function () {
    if ($(this).text() == $(this).prev().text()) $(this).remove()
})

jsFiddle example

Upvotes: 2

Related Questions