Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty array values ("") from an array?

I have an two dimensional array, generated from a html table with jQuery, but some values are empty so "" is displayed.

How can I remove the empty values?

  <table>    
    <tr>
      <th>1A</th>
      <th>1B</th>
      <th>1C</th>
    </tr>
    <tr>
      <td>2A</td>
      <td>2B</td>
      <td>2C</td>
    </tr>
    <tr>
      <td></td>
      <td>3B</td>
      <td>3C</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td>4C</td>
    </tr>
  </table>
<script>
    var columns = $('tr').first().children().map(function(i) {
        return [
            $('tr').map(function(){
                return $(this).children().eq(i).text()
            }).get()
        ]
    }).get();
<script>

I already tried following code:

for( var i = 0; i < columns[0].length; i++){ 
   if ( columns[0][i] === "") {
    columns[0].splice(i, 1); 
   }
}

It worked for some empty values, but not all of them got removed for some reason.

Output: https://imgur.com/e7BAdQK

like image 279
House97_ Avatar asked Apr 15 '19 08:04

House97_


People also ask

How do you remove Blank strings from an array?

To remove the empty strings from an array, we can use the filter() method in JavaScript. In the above code, we have passed the callback function e => e to the filter method, so that it only keeps the elements which return true . empty "" string is falsy value, so it removes from the array.

Can an array have empty values?

An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.


Video Answer


3 Answers

Try filtering with the Boolean function:

columns.filter(Boolean)

This will filter out all falsy values

like image 30
thedude Avatar answered Sep 20 '22 03:09

thedude


You could use the filter like:

arr = arr.filter(item => item);

Example:

let arr = ['One', 'Two', '', 'Four', '', ''];
arr = arr.filter(item => item);
console.log(arr);

// Result
// ['One', 'Two', 'Four']

Because an empty string evaluates to boolean false. It works with all falsy values like 0, false, null, undefined, '', etc.

DEMO

If you want to keep some values like number 0 (zero) you could use item !== undefined. This filters only undefined values. Keep in mind to trim your string or check with regex to ensure empty strings without whitespaces.

like image 188
Dominik Avatar answered Sep 20 '22 03:09

Dominik


It's because when you columns[0].splice(i, 1); you are changing the same array you are iterating over so you might want to use an array filter like

columns[0] = columns[0].filter((val) => val != "");

instead of the for loop

like image 26
sassy_rog Avatar answered Sep 17 '22 03:09

sassy_rog