Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 02 of 30 · Pathway 1 — Spreadsheet Automation

Smart Data Cleaning Tool

Duplicate and malformed contacts pollute mailing lists. Normalize and validate contact records without modifying originals.

Real-world benefit
Volunteer lists, event registrations and customer records.
Technologies
Google Sheets, Regular expressions, Set, Batch writes
Required knowledge
Basic spreadsheet use. Regular expressions are explained in the walkthrough.
Time and level
About 25 minutes · Beginner
AI requirement
None: deterministic Apps Script
Expected baseline
One valid unique contact; three issue rows (invalid email, duplicate, missing name).

Loading the interactive studio…

Introduction

Trim and lowercase before checking the Set; original row numbers identify rejected records. The application's entry point is cleanContacts(). Baseline limitation, as stated in the workshop: Email regex checks shape only, not deliverability.

Key building blocks: trim(); toLowerCase(); Set; regular expressions; batch writes.

Practical use cases

Volunteer lists, event registrations and customer records.

Prerequisites

  • Basic spreadsheet use. Regular expressions are explained in the walkthrough.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Contacts" (fictional)
NameEmailCity
Alice Johnson ALICE@example.com Toronto
Bobbad-emailOttawa
Alice Johnsonalice@example.comToronto
eve@example.comAjax

Setup in your own Google account

  1. Download 02-smart-data-cleaning-tool.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Contacts, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  6. Check the result: One valid unique contact; three issue rows (invalid email, duplicate, missing name).

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 02-smart-data-cleaning-tool at commit 4a26d919, SHA-256 dc7f68f54b9b. Unchanged.

// Smart Data Cleaning Tool
// Entry point: cleanContacts; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","cleanContacts").addToUi();}
function cleanContacts(){
// Normalize values before checking duplicates; retain source row numbers.
const seen=new Set(),clean=[],issues=[]; const s=SpreadsheetApp.getActive().getSheetByName('Contacts'); s.getDataRange().getValues().slice(1).forEach((r,i)=>{if(r.every(v=>v===''))return; const [n,e,c]=r.map(v=>String(v).trim()); const email=e.toLowerCase(); const issue=!n?'Missing name':!/^\S+@\S+\.\S+$/.test(email)?'Invalid email':seen.has(email)?'Duplicate':''; if(issue)issues.push([i+2,issue]); else {seen.add(email);clean.push([n,email,c]);}}); output('Clean',['Name','Email','City'],clean);output('Issues',['Row','Issue'],issues);
}
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }

How the code works

Beginner explanation

cleanContacts() reads each contact, tidies spaces and lower-cases the email, then decides whether the row is clean or has an issue. Clean rows go to a Clean tab and problems go to an Issues tab with the original row number. The Contacts tab is never changed.

Technical explanation

Each row is destructured after map(v=>String(v).trim()). A chained conditional assigns the first matching issue: missing name, invalid email (regex /^\S+@\S+\.\S+$/), or duplicate (Set of normalized emails). Only accepted emails are added to seen, so an invalid row never blocks a later valid one. Issues keep i+2 so the row number matches the sheet (header + 1-based).

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function cleanContacts(){
// Normalize values before checking duplicates; retain source row numbers.
const seen=new Set(),clean=[],issues=[]; const s=SpreadsheetApp.getActive().getSheetByName('Contacts'); s.getDataRange().getValues().slice(1).forEach((r,i)=>{if(r.every(v=>v===''))return; const [n,e,c]=r.map(v=>String(v).trim()); const email=e.toLowerCase(); const issue=!n?'Missing name':!/^\S+@\S+\.\S+$/.test(email)?'Invalid email':seen.has(email)?'Duplicate':''; if(issue)issues.push([i+2,issue]); else {seen.add(email);clean.push([n,email,c]);}}); output('Clean',['Name','Email','City'],clean);output('Issues',['Row','Issue'],issues);
}

Common mistakes

  • Checking duplicates before normalizing, so ALICE@ and alice@ look different.
  • Writing cleaned values back over the source tab, which destroys the evidence.
  • Treating the email regex as proof the address exists; it checks shape only.

Run it and expected output

Choose Workshop → Run application (runs cleanContacts()). Expected: One valid unique contact; three issue rows (invalid email, duplicate, missing name).

Original workshop exercise

Correct Bob's email to bob@example.com; expect two clean rows and two issues.

Troubleshooting and debugging

The tab was renamed

A colleague renamed the Contacts tab to "contacts". The cleaner now crashes with a confusing message.

Fix: Rename the tab back to exactly "Contacts".

getSheetByName() returns null instead of throwing, so the error appears one step later as "Cannot read properties of null". Project 01's input() helper avoids this by throwing "Missing tab: …" immediately.

Duplicates slip through

After an edit, both Alice rows appear in Clean.

Fix: Normalize the email with toLowerCase() before checking the Set.

Duplicate detection only works on normalized values. Decide the normalization rules (trim, lower-case) before comparing.

Extension activity: Preview proposed changes

Without changing Contacts, add a Changes tab listing every value the cleaner would change: row, field, before and after.

Acceptance checks:

  • Clean and Issues are unchanged
  • Changes lists the trimmed name and lower-cased email for row 2
  • Contacts is still the original data

Original improvement idea from the workshop: Add configurable required fields and a preview of proposed changes.

Extension prompt
Update the existing app without removing working features. Add configurable required fields and a preview of proposed changes. Return complete updated files, explain changes and give regression tests.
Automation option: Run after a batch import; keep Issues for human review. Keep this separate from the baseline exercise.

Automation considerations

Rerun-safe: Clean and Issues are rebuilt each run and Contacts is never modified. Schedule after a batch import and keep Issues for human review.

Workshop note: Run after a batch import; keep Issues for human review.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 02: Smart Data Cleaning Tool. Input tab Contacts, exact headers: Name, Email, City. Create cleanContacts() that trims fields, lowercases emails, flags missing names and invalid emails, deduplicates valid emails and writes Clean and Issues tabs with source row numbers. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: One valid unique contact; three issue rows (invalid email, duplicate, missing name). Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point cleanContacts and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/02-smart-data-cleaning-tool. Base version limitations: Email regex checks shape only, not deliverability.

Knowledge check

  1. Why does the Issues tab report row 3 for Bob instead of row 2?

    1. The code adds 2 to the array index: one for the header and one because sheets count from 1
    2. Bob is actually on row 3 of the array
    3. Issues are sorted alphabetically
    Answer

    The code adds 2 to the array index: one for the header and one because sheets count from 1 Correct: slice(1) removes the header, and index 0 is sheet row 2, so i+2.

  2. Which value would the email regex accept even though it is not a working address?

    1. nobody@nowhere.invalid
    2. bad-email
    3. alice@
    Answer

    nobody@nowhere.invalid Correct: the regex only checks the shape something@something.something.

  3. A contact row is completely blank. What happens to it?

    1. It is skipped and not reported
    2. It becomes a Missing name issue
    3. The run stops
    Answer

    It is skipped and not reported Correct: if(r.every(v=>v===''))return; skips empty rows.

  4. Clean shows two Alice rows after someone edited the code. What is the most likely cause?

    1. The email is no longer lower-cased before the duplicate check
    2. The Set was replaced with an array
    3. trim() was removed from the name
    Answer

    The email is no longer lower-cased before the duplicate check Correct: ALICE@example.com and alice@example.com only match after normalization.

  5. Should this cleaner overwrite the Contacts tab with the cleaned data?

    1. No: keep the source and write results to separate tabs so changes can be reviewed and undone
    2. Yes, it saves space
    3. Yes, but only on Fridays
    Answer

    No: keep the source and write results to separate tabs so changes can be reviewed and undone Correct: preserving the source is the workshop rule and makes errors recoverable.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Duplicate and malformed contacts pollute mailing lists. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Contacts tab and its headers: Name, Email, City. Say what goes in and what should come out.
    Narration: Duplicate and malformed contacts pollute mailing lists. Practical uses: Volunteer lists, event registrations and customer records.
  2. 0:45–1:30 — Predict and run. Ask the room: How many rows will the Clean tab contain (not counting the header)? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: One valid unique contact; three issue rows (invalid email, duplicate, missing name).
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select cleanContacts() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: cleanContacts() reads each contact, tidies spaces and lower-cases the email, then decides whether the row is clean or has an issue. Clean rows go to a Clean tab and problems go to an Issues tab with the original row number. The Contacts tab is never changed.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Contacts tab, click cell B3, type bob@example.com in the formula bar and press Enter. Click ▶ Run application again.
    Narration: Workshop challenge: Correct Bob's email to bob@example.com; expect two clean rows and two issues.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Rerun-safe: Clean and Issues are rebuilt each run and Contacts is never modified. Schedule after a batch import and keep Issues for human review.
    Narration: Baseline limitation: Email regex checks shape only, not deliverability.

Closing takeaway: Trim and lowercase before checking the Set; original row numbers identify rejected records.

Related resources