skip to Main Content

I’m having an issue retrieving email addresses from the 3rd col in an array (obtained from a Gsheet) using filter and map functions. The call is printing an empty array in the log. Can someone please explain what I’m doing wrong?

Here is the function:

/**
 * Retrieves email addresses from a sheet based on selected names from a form.
 *
 * @param {object} e - Form submit event object.
 * @return {string} - A comma-separated string of email addresses.
 */
function getEmailAddresses(e) {
  // Get the responses from the form.
  const responses = e.response.getItemResponses();

  // Extract the selected names from the checkboxes.
  const eList = responses.find(item => item.getItem().getTitle() === 'E List').getResponse();

  // Get the spreadsheet and sheet.
  const ss = SpreadsheetApp.openById("SHEET_ID");
  const shet = ss.getSheetByName('ECI');

  const data = shet.getRange(2, 1, shet.getLastRow()-1, 3).getValues();

  // Logger.log(data);

  // Filter the data based on selected names and extract email addresses.
  // Assuming first name is in column 1 and last name in column 2
  // Assuming email is in column 3
  const emailAddresses = data.filter(row => eList.includes(`${row[0]} ${row[1]}`)).map(row => row[2]);
  Logger.log(emailAddresses);

  // Return the email addresses as a comma-separated string.
  return emailAddresses.join(',');
}

eList

First Last Email Phone
A a [email protected] 12345
B b [email protected] 67890
C c [email protected] 12346

data

2

Answers


  1. Assuming that the data you have actually looks like what you provided in your comment, this should do what you want.

    const data = [
      ['A', 'a', '[email protected]'],
      ['B', 'b', '[email protected]'],
      ['C', 'c', '[email protected]'],
      ['D', 'd']
    ];
    
    const emailAddresses = data.map((listItem) => listItem[2] || false).filter(Boolean);
    
    console.log('emailAddresses: ', emailAddresses);
    Login or Signup to reply.
  2. To get matching values you need to iterate eList for every row of data:

    const emailAddresses = data.filter(row => eList.some(fRow => row[0] === fRow[0] && row[1] === fRow[1])).map(row => row[2]);
    

    The double iteration is achieved through .filter on the data and .some on the eList, comparing only firstnames([0]) and last names([1]). if eList has many rows, it maybe wise to create a Set of eListNames and eListEmailAddresses for comparison. I assume eList is small compared to data and therefore prefer the lazy double loop as shown above.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search