Question

is there a way I can create an array using jQuery / JS that contains all unique values from a table, i.e. without duplicates ? Also, the values I would be interested in are only in TDs with a certain class (myClass) + I would like to exclude "" and " " as non-valid values.

In the below example the output should be [item1,item2,item3] as the only unique and valid values.

Example table:

<table id="myTable">
    <thead>
        <tr>
            <th class="myHeader">Cat 1</th>
            <th>Vol 1</th>
            <th class="myHeader">Cat 2</th>
            <th>Vol 2</th>
            <th class="myHeader">Cat 3</th>
            <th>Vol 3</th>
            //...
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="myClass">item1</td><td>8</td><td class="myClass">item2</td><td>7</td><td class="myClass">item1</td><td>2</td>
        </tr>
        <tr>
            <td class="myClass">item3</td><td>5</td><td class="myClass">item2</td><td>7</td><td class="myClass">item2</td><td>4</td>
        </tr>
        <tr>
            <td class="myClass">item3</td><td>1</td><td class="myClass">item1</td><td>5</td><td class="myClass">item3</td><td>3</td>
        </tr>
        //...
    </tbody>
</table>

My JS so far (not covering duplicates):

var result = new Array();
$('td').each(function() {
    if( ($(this).text() != '') && ($(this).text() != ' ') {
        result.push(+($(this).text()));
    }
});
alert(result);

Many thanks in advance, Tim.

Was it helpful?

Solution

Try this

var result = new Array();
$('td').each(function() {
    if( ($(this).text() != '') && ($(this).text() != ' ') {
        if(result.indexOf($(this).text()) == -1){
            result.push(+($(this).text()));
        }
    }
});
alert(result);

OTHER TIPS

You can use $.unique() after:

result = $.unique(result);

or check beforehand:

if(result.indexOf(this.textContent) == -1){
    //push
}

You can do this:

var result = new Array();

$('#myTable').find('td.myClass').each(function () {
   if (result.indexOf($(this).text()) == -1) {
       result.push($.trim($(this).text()));
   }
});
console.log(result);

Fiddle


With $.inArray():

var result = [];

$('#myTable').find('td.myClass').each(function () {
   if ($.inArray($(this).text(), result) == -1) {
      result.push($.trim($(this).text()));
   }
});
console.log(result);

With jQuery.inArray()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top