33

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://i.sstatic.net/LvMSt.jpg

4

11 Answers 11

107

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.

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

1 Comment

Worked in Google Apps Script too.
19

Try filtering with the Boolean function:

columns.filter(Boolean)

This will filter out all falsy values

Comments

4

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

1 Comment

you shouldn't be using !=, this is bad practice.
3

after creating the columns array,

filter the empty values like that

columns = columns.filter((v) => v != '')

Comments

2

Just use filter function:-

columns = columns.filter(col => col);

It will remove empty values.

Comments

2

If some values might be 0, filter by checking against "" (because 0 evaluates to false as well, so Boolean checks will fail for 0):

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

Comments

1

In ES6, Lets say you have the following array:

arr = [1, 2, 3, '', false, '4'];

And you want to remove '' (Which is an empty value) from the array. You can do:

const filter = (...args) => args.filter(el => el !== '');
console.log(filter(...arr));
[1, 2, 3, false, "4"] // Output

Or Using Map (Regular JS)

const myArr = [1, 2, '', '4'];

noEmptyStringInThisArray = [];

myArr.map((elem) => {
    if (elem !== '') {
    noEmptyStringInThisArray.push(elem);
    }
})

console.log(noEmptyStringInThisArray);
// [1, 2, "4"]

1 Comment

For es6, that is quite a clunky way to remove empty strings. You can also: arr.filter(val => val);
1

i'm pretty surprised nobody gave the right accurate answer here.

in all of the Boolean based expressions here, you'd filter the results that you'd want to keep. for instance - "0", etc.

array.filter(item => item !== '')

Comments

1

Supposing an array like this ['ABC123', '', 0, '0', ' ', null, undefined, empty]

and you consider "empty" '' or ' ' or null or undefined or empty but not 0

my_array = my_array.filter(item => item && (item.toString().replace(/\s+/,'') || item === 0));

the result is ['ABC123', 0, '0']

Comments

0

Easily you can remove empty , null , undefined values from an array.

let my_array = ['One', undefined, 'Two', '', null, 'Four', '', '', 'Five'];

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

console.log(my_array);

Comments

0

In case some types of falsy values need to be preserved, filter to include those before checking if the value is truthy. The example below preserves a numeric zero, but removes anything else that would be considered empty.

Conversely, specific types of empty values can be filtered out.

Finally, if there's no complexity about what empty means or does not mean, a simple check for a truthy value works.

let values = [0, 1, 0.0, 1.0, '0', '1', true, false, '', , null, undefined];

//keep numeric, remove all other empty values
console.log(values.filter(x => [0].includes(x) || x));

//only remove certain types of empty values
console.log(values.filter(x => ![null, undefined].includes(x)));

//only keep truthy values, remove all falsy values
console.log(values.filter(x => x));

Comments

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.