Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove undefined elements from array

I have a table where I pull data and add it to an array of arrays. The problems is if one of the table cells is empty it appears in the array as "undefined". I tried using an if the last element is undefined if so using .pop() the element should be removed. I still get undefined elements. Here's my code and live demo

HTML :

<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"></td>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Anthony</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
</table> 


JavaScript :
//IE9+ compatable solution
$(function(){
    var results = [], row; 
    $('#contactlisttable').find('th, td').each(function(){
        if(!this.previousElementSibling){ //New Row?
            row = []; 
            results.push(row); 
            if($(this) === 'undefined'){//Remove undefined elements
                row.pop();
            }
        }
        row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)       
    }); 
    console.log(results); 
}); 

like image 941
user2882684 Avatar asked Feb 25 '26 03:02

user2882684


1 Answers

jsFiddle Demo

Instead of doing the conditional statements, just take advantage of your html structure. First select by the table rows, and then iterate the child td or th elements. You can also take advantage of jQuery's text instead of doing the feature detection. jQuery's text will be more reliable.

var results = [];
$('#contactlisttable tr').each(function(){
 var row = [];
 $(this).find('td,th').each(function(){
     row.push($(this).text());
 });
 results.push(row);
});
console.log(results);
like image 154
Travis J Avatar answered Feb 27 '26 16:02

Travis J