shiva
shiva

Reputation: 223

Find duplicated data in a HTML table

I have a table in my HTML, and in this table the individual values within the <td> tags are generated from an Javascript array.

I want to compare the values contained in the <td> tags against each other and check for duplicates.

Upvotes: 1

Views: 10928

Answers (1)

nnnnnn
nnnnnn

Reputation: 150050

<td> elements don't have a value, they have contents (that may or may not include other elements). If your question is "How do I check that no two td elements have the same contents?" you can do something like this:

var contents = {},
    duplicates = false;
$("#yourtableidhere td").each(function() {
    var tdContent = $(this).text();
    if (contents[tdContent]) {
        duplicates = true;
        return false;
    }
    contents[tdContent] = true;
});    
if (duplicates)
   alert("There were duplicates.");

You don't say when this process should occur, but if in response to the user clicking a button or something then put the above code in a click event handler.

Demo: http://jsfiddle.net/FA6SR/

Obviously you can expand the above to note exactly which cells had duplicate values, what the values were, etc.

EDIT - P.S. You mention that the values come from an array. It would be just as easy to code the comparison test against the array rather than against the table cells, but more efficient at runtime. jQuery wouldn't really help with that, you'd just use a standard for loop.

Upvotes: 5

Related Questions