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 | Phone | |
---|---|---|---|
A | a | [email protected] | 12345 |
B | b | [email protected] | 67890 |
C | c | [email protected] | 12346 |
data
First | Last | |
---|---|---|
A | a | [email protected] |
B | b | [email protected] |
C | c | [email protected] |
2
Answers
Assuming that the data you have actually looks like what you provided in your comment, this should do what you want.
To get matching values you need to iterate
eList
for everyrow
ofdata
:The double iteration is achieved through
.filter
on thedata
and.some
on theeList
, comparing only firstnames([0]
) and last names([1]
). ifeList
has many rows, it maybe wise to create aSet
ofeListNames
andeListEmailAddresses
for comparison. I assumeeList
is small compared todata
and therefore prefer the lazy double loop as shown above.