0

I am using the code to remove duplicates as explained here: jQuery Remove Duplicate Elements. It works perfectly, but I cannot find the code to show the number of times a duplicate was removed for each element. I think it's quite simple, but I'm not very experienced with jquery.

RESOLVED thanks to shaunakde

var seen = {};
var counter = {};
var length = $('#links1 a, #links2 a').length;
console.log(length);
$('#links1 a, #links2 a').each(function(i) {
var txt = $(this).text();
if(seen[txt]){
    $(this).remove();
    counter[txt]++;
}
else{
    seen[txt]=true;
    counter[txt] = 1;
}
if(i==(length-1)){

    $.each(counter , function(i, val) { 
          $('a:contains('+i+')').html(i+' ('+val+')')

});

}

});

It now correctly prints out: - Item 1 (4) - Item 2 (1) - Item 3 (5)

Where the number between brackets is the number of times it was removed (+1).

Community
  • 1
  • 1

2 Answers2

1

Here is a working Demo Fiddle

var seen = {};
var counter = {};
var length = $('#links1 a, #links2 a').length;              //Length of <a> elements
console.log(length);
$('#links1 a, #links2 a').each(function(i) {
    var txt = $(this).text();
    if(seen[txt]){
        $(this).remove();
        counter[txt]++;
    }
    else{
        seen[txt]=true;
        counter[txt] = 1; 
    }
    if(i==(length-1)){                                      //Last iteration

        $.each(counter , function(i, val) { 
            $('p#first').append('<p>'+i+': '+val+'</p>');   //Print Text and its Occurence.
        });


    }

});

You just had to print all the Values and Indexes after the last iteration.

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
0

Well I'd recommend you to create an additional Array that counts the duplicates for each text

counters = Array();

if (seen[txt]) {
    $(this).remove();
    count++;
    counters[txt]++; 
} else {
    seen[txt] = true;
    counters[txt] = 1;
}
Tobias Baumeister
  • 2,107
  • 3
  • 21
  • 36