2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Fancy or not it works good sir! Thank you kindly! Think I got my head too wrapped around the .map() and .toArray() functions that I missed the obvious :)
0

try this :

var outerArray = new Array() ;

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

1 Comment

I fixed some of the code errors in your answer to make it work, but it just places the jQuery Object of the element <td> into the array. I need to be able to reference that data as a multidimensional array like: var data = outerArray[0][2]; Having it in element Object form doesn't really help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.