Reputation: 11377
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.
Upvotes: 1
Views: 4311
Reputation: 74738
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);
With $.inArray()
:
var result = [];
$('#myTable').find('td.myClass').each(function () {
if ($.inArray($(this).text(), result) == -1) {
result.push($.trim($(this).text()));
}
});
console.log(result);
Upvotes: 0
Reputation: 2511
You can use $.unique()
after:
result = $.unique(result);
or check beforehand:
if(result.indexOf(this.textContent) == -1){
//push
}
Upvotes: 2
Reputation: 1126
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);
Upvotes: 2