Reputation: 1077
I am attempting to place text from a <table>
into a an array, as an array of text.
Sample HTML:
<table class="sort">
<caption>Census Data</caption>
<tr>
<th class="alpha">First Name:</th>
<th class="alpha">Last Name:</th>
<th class="date">Date of Birth:</th>
<th class="numeric">Age:</th>
<th class="alpha">Gender:</th>
</tr>
<tr>
<td>Peter</td>
<td>Parker</td>
<td>12/23/1975</td>
<td>36</td>
<td>Male</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>06/09/1982</td>
<td>30</td>
<td>Male</td>
</tr>
</table>
Ultimate goal it to have an array like this:
var array = [
["Peter", "Parker", "12/23/1975", "36", "male"],
["John", "Doe", "06/09/1982", "30", "male"]
];
This is what I currently have, my problem seems to be with me inner return not actually being an array when it reaches the outer map. When I alert(innerArray.toString());
it gives me the comma separated string as if it is a string inside, but on the outside it seems to join
the arrays into one rather than make it multidimensional.
var outerArray = $(".sort tr").not(":first-child").map(function(){
var innerArray = $(this).children().map(function(){
return $(this).text();
}).toArray();
return innerArray;
}).toArray();
Upvotes: 2
Views: 1566
Reputation: 46657
There's probably some fancy way to do it with map, but I prefer just looping via each
as it is easier to understand and maintain.
var resultArray = [];
$(".sort tr").not(":first-child").each(function () {
var innerArray = [];
$(this).find('td').each(function () {
innerArray.push($(this).text());
});
resultArray.push(innerArray);
});
Upvotes: 2
Reputation: 1681
try this :
var outerArray = new Array() ;
$('.sort').children('tr').each(function(i,elem) {
outerArray.push(elem.children('td')) ;
});
Upvotes: 0