30

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.stack.imgur.com/LvMSt.jpg

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
House97_
  • 373
  • 1
  • 3
  • 10
  • Some demo code would be nice. Use jsfiddle or something please. As the blanks may be coming from many different things. – Deckerz Apr 15 '19 at 08:20
  • 3
    right after the for loop add `columns = columns.filter(a => a!="")` – alt255 Apr 15 '19 at 08:20
  • 5
    Possible duplicate of [Remove empty elements from an array in Javascript](https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript) – jeprubio Apr 15 '19 at 08:24
  • Possible duplicate of [Remove empty strings from array while keeping record Without Loop?](https://stackoverflow.com/questions/19888689/remove-empty-strings-from-array-while-keeping-record-without-loop) – adiga Apr 15 '19 at 08:57

10 Answers10

100

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.

Domske
  • 4,795
  • 2
  • 20
  • 35
17

Try filtering with the Boolean function:

columns.filter(Boolean)

This will filter out all falsy values

thedude
  • 9,388
  • 1
  • 29
  • 30
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

sassy_rog
  • 1,077
  • 12
  • 30
3

after creating the columns array,

filter the empty values like that

columns = columns.filter((v) => v != '')
shushu304
  • 1,506
  • 1
  • 7
  • 15
2

Just use filter function:-

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

It will remove empty values.

S K
  • 442
  • 3
  • 5
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 != "");
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
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"]
codedbychavez
  • 193
  • 4
  • 6
  • 1
    For es6, that is quite a clunky way to remove empty strings. You can also: `arr.filter(val => val);` – vizon Apr 13 '22 at 15:05
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 !== '')

bugkiller
  • 124
  • 3
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']

MTK
  • 3,300
  • 2
  • 33
  • 49
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);
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25