1

I need to get data from a table and store it in an array. Each row of the table should be a new array within an array. Basically the html looks like this:

<table id="contactlisttable">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Phone</th>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Joey</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Anthony</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
</table> 

ect...

Here is my code

jQuery(document).ready(function(){
    $(function(){
        var $table = $("#contactlisttable"),
        $headerCells = $table.find("tr th"),
        $myrows = $table.find("tr"); // Changed this to loop through rows

        var headers = [],
            rows = [];

        $headerCells.each(function() {
            headers[headers.length] = $(this).text();
        });

        $myrows.each(function() {
            $mycells = $myrows.find( "td.contactlist" ); // loop through cells of each row
            cells = []
            $mycells.each(function() {
                cells.push($(this).text());
            });
            if ( cells.length > 0 ) {
                rows.push(cells);
            }  
        });
        console.log(headers);
        console.log(rows);
    }); 
});

my current code out puts

[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],

the desired output would be:

["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]
user2882684
  • 539
  • 1
  • 5
  • 10

1 Answers1

0

I think this can be simpler:

Live Demo

JS

$(function(){
    var results = []; 
    var row = -1; 
    $('#contactlisttable').find('th, td').each(function(i, val){
        if(i % 3 === 0){ //New Row? 
            results.push([]); 
            row++;//Increment the row counter
        }
        results[row].push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)       
    }); 
    console.log(results); 
}); 

EDIT

Here's an even better solution (IE9+ compatible). It accounts for variable row lengths unlike my previous solution.

Live Demo

JS

//IE9+ compatable solution
$(function(){
    var results = [], row; 
    $('#contactlisttable').find('th, td').each(function(){
        if(!this.previousElementSibling){ //New Row?
            row = []; 
            results.push(row); 
        }
        row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)       
    }); 
    console.log(results); 
}); 
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
  • great! can i fit .text() in there instead of .innerHTML so there's no html? – user2882684 Dec 12 '13 at 20:22
  • Sure, just change `this.innerHTML` to `$(this).text()` although using `this.innerText || this.textContent` will be more performant as it removes the unnecessary conversion of `this` to a jQuery object and maintains compatibility with firefox. – Brandon Boone Dec 12 '13 at 20:35
  • ok looks great, I'm having trouble understanding line 5 this is to add the tr's into inner arrays? – user2882684 Dec 16 '13 at 16:16
  • This line:`if(i % 3 === 0)`? If so, `%` is the [remainder operator](http://stackoverflow.com/questions/16505559/how-can-i-use-modulo-operator-in-javascript). It returns the remainder of dividing these two numbers together. I use it to find out where each row starts, using 3 since there are 3 `td` per row. To play out the sequence: `0 % 3 = 0`(New row), `1 % 3 = 2`, `2 % 3 = 1`, `3 % 3 = 0`(New row), `4 % 3 = 1`, `5 % 3 = 2`, `6 % 3 = 0`(New row), .... As you can see, the pattern demarcates the rows in the grid by returning 0. We use this flag to know when to add our sub arrays. – Brandon Boone Dec 16 '13 at 17:41
  • What if one or more of the table cells is empty? I am getting the value "undefined" in the array. is it possible to check for empty cells so they are not added to the array or should undefined values later be removed from the array? – user2882684 Dec 23 '13 at 15:12
  • this is a snippet of code I have found in my research that I've been struggling with implementing http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript – user2882684 Dec 23 '13 at 15:12
  • I have also tried to removed undefined elements using .pop() [link](http://jsfiddle.net/3Tqxz/5/) – user2882684 Dec 23 '13 at 15:21