Filter Out Blank Rows


What you'll need

Before you can filter anything, you'll need a data set to filter by. More specifically, you'll need a data Array. An array is a collection of data, formatted like a grid and displayed using square brackets [].

You can have flat arrays which look like this:

[1,2,3,4,5]

Or nested arrays which look like this:

[ [1,2,3], [4,5,6], [7,8,9] ]

How to use the .filter() method

When you have a data array, you can call a javascript method called .filter() to have the code quickly iterate through the data set and return only what you want from it. In this code snippet, we'll be filter out anything that is blank - or in the inverse case, we'll only return the array positions which have a value.

Let's take this flat array as an example:

let array = ['hello','','world']

If we tried to loop through this and use it as is, we would have to deal with a blank value after processing 'hello'. To filter that out, we can do something as simple as this:

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

To filter out a nested array, we'll need to also specify the position in the nested array we want to filter out the blanks by.

Let's take this nested array as an example:

let array = [ ['name', 'age'], ['John','38'], ['Jimmy',''], ['Jane','35'] ]

In this scenario, we have a data set that contains 3 people and their ages. Except, we don't have Jimmy's age, so we want to exclude Jimmy's data when we begin processing the data set. Using the same filter() method from above, we just need to tweak it a bit to remove Jimmy's row:

array.filter(x => x[1] !== '')

We use 1 here because array positions always start from 0.



How to use this code snippet

This filterOutBlankRows() code snippet takes in two parameters into it - the data set, and the target column number you want to filter out blanks for.

function filterOutBlankRows(data, targetColumnNum) { const filteredData = data.filter((row) => row[targetColumnNum-1] !== "") return filteredData }

Taking a look at the previous data set again, you can get the same result by calling the function like this:

let array = [ ['name', 'age'], ['John','38'], ['Jimmy',''], ['Jane','35'] ] filterOutBlankRows(array, 2)

Notice that we're saying 2 for the targetColumnNum instead of 1 like we did for the array position. This is just to make it easier for you when counting the columns within your data set since you're probably working with a Google Sheet. Column A = 1, Column B = 2, and so on.

Speaking of Google Sheet data, make sure to check out the code snippet for pulling data from a Google Sheet so that you can combine this snippet with that one.

thumbnail

NitroGAS Chrome Extension

Want to reference this code snippet right from your Google Apps Script Project? Check out our NitroGAS Chrome Extension. This tool will help you build your scripts faster than you could imagine. The tool itself and access to the code snippets are 100% FREE - Happy Coding!

Get the Extension