Iron3eagle
Iron3eagle

Reputation: 1077

Create Multidimensional Array From Table Text

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

Answers (2)

jbabey
jbabey

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);
});

Working example.

Upvotes: 2

Cyril ALFARO
Cyril ALFARO

Reputation: 1681

try this :

var outerArray = new Array() ;

$('.sort').children('tr').each(function(i,elem) {
     outerArray.push(elem.children('td')) ;
});

Upvotes: 0

Related Questions