Home:ALL Converter>Is there a way to filter an array for strings in google apps script?

Is there a way to filter an array for strings in google apps script?

Ask Time:2021-03-19T18:16:14         Author:ChSoLu

Json Formatter

I am trying to filter the array 'employee_name' consisting of NaNs and one string element, to exclude any element BUT the string. The context is that I have a spreadsheet containing employee's birth dates, and I'm sending an email notification in case there's a birthday two days from today. My variables look like this:

var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Employees');
  var range = ss.getRange(2, 1, ss.getLastRow()-1, 1); // column containing the birth dates
  var birthdates = range.getValues(); // get the `values` of birth date column
  var today = new Date ();
  var today = new Date(today.getTime());
  var secondDate = new Date(today.getTime() + 48 * 60 * 60 * 1000);
  var employee_name = new Array(birthdates.length-1);

And the loop:

for (var i=0;i<=birthdates.length-1;i=i+1){

    var fDate = new Date(birthdates[i][0]);
if (fDate.getDate() == secondDate.getDate() && 
        fDate.getMonth() == secondDate.getMonth()){

        //define variables for outgoing email

        for (var j=0; j<=birthdates.length-1;j=j+1){
          employee_name[j] = [NaN];
        } 
        employee_name[i] = ss.getRange(i+2,6);
        employee_name[i] = employee_name[i].getValues();
}
}

after which the array in question looks like this

Logger.log(employee_name);

[[[Mia-Angelica]], [NaN], [NaN], [NaN], ..., [NaN]] I have already tried the filter(Boolean), but this isn't working:

employee_name_filtered = employee_name.filter(Boolean);
Logger.log(employee_name_filtered);

returns [[[Mia-Angelica]], [NaN], [NaN], [NaN], ..., [NaN]]. I have also tried filling the non-string array entries with numeric values (instead of NaN) and then apply

employee_name_filtered = employee_name.filter(isFinite);
Logger.log(employee_name_filtered);

returns [[1.0], [2.0], [3.0], ..., [72.0]], so this filter method is working, but then I would need the 'inverse' of that because I want to keep the string.

I need the array within array to store the values at the position of the counter variable where the condition's met (similar to How to store data in Array using For loop in Google apps script - pass array by value).

This is my first time posting a question on SO, so if I overlooked any 'rules' about posting, just let me know and I will provide additional info. Any help will be appreciated!

EDIT:

what I would like to receive in the end is simply [[Mia-Angelica]].

Author:ChSoLu,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/66706262/is-there-a-way-to-filter-an-array-for-strings-in-google-apps-script
yy