Mark Duplicates in Table

Hello all,

With the following code I’m trying to mark values, that occur in the table more than once, red.
I searched the internet and found some solutions that mark only the duplicates and not the first occurrence.

The code below however does not work (does not mark duplicates)

Thwe code goes as follows:
first it loops through the table and pushes all values in an array
In the second loop it checks if the value already exists in the array and if so, it should be marked red.

Any ideas?


 function findDuplicatesInTable(){
    var column = 1;
    var arrDup = [];

    $('#excel_table td:nth-child(' + column + ')').each(function() {
        arrDup.push(this.innerHTML);
    });    
    
    $('#excel_table td:nth-child(' + column + ')').each(function() {
        var numOccurences = $.grep(arrDup, function (elem){
            return elem === this.innerHTML;
        }).length;
    
        if(numOccurences > 1){
            $(this).css('color', "red")
        }
    });
}

Within the $.grep() function, this does not refer to the element any more but to the window object. As a way around this, you could either use an arrow function, or .bind() the iteratee to the outer this context (which would be the IE-compatible solution).

May I ask you to show how use these in this particular situation.
I never used these function before.

Like

// Arrow functions never have a dynamic `this`, so it
// refers to the `this` in the surrounding scope
var numOccurences = $.grep(arrDup, elem => {
  return elem === this.innerHTML;
}).length

// Or explicitly .bind(this) to the iteratee
var numOccurences = $.grep(arrDup, function (elem){
  return elem === this.innerHTML;
}.bind(this)).length

You helped me a lot with this, Thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.