JavaScript examples: lists and arrays
Get a list into Run Custom Code and work with it: dedupe, top items, batches, merges, CSV text and comparisons. Use Aggregate for totals.
- Verified Nov 17, 2026
- Classic builder
On this page
- Before you start
- How a list gets into your code
- Turn comma-separated text into a clean list
- Remove duplicates from a list
- Pick a random item
- Top items by a number
- Split a list into batches
- Merge two lists and drop duplicates by id
- Turn a list of objects into CSV text
- Find what is in one list but not the other
- Shuffle a list and pick winners
Snippets for a Run Custom Code step that work with a list of values or records: removing duplicates, picking the top items, splitting into batches, merging, building CSV text and comparing two lists. For how the step works, see Run custom JavaScript in a workflow.
Before you start #
- Add the step Add a Run Custom Code step to your workflow and leave Language set to JavaScript.
- Add the inputs Under Data to use in the code, click + Add Input once for each input the snippet lists. Type the name from the snippet in Variable name and choose where the value comes from, for example Record Value (Source) or Custom Value.
- Paste and test Click the Code box to open the code editor, paste the snippet, and click Run. The Response tab shows what the code returned.
- Use the results In a later step, open the value picker, choose Step Data, pick this step, and pick the key the snippet returned (for example
full_name).
An input is available in the code as $ followed by its variable name: an input named first_name is $first_name. Add every input a snippet uses; a name with no matching input stops the code with a "not defined" error.
How a list gets into your code #
Add an input under Data to use in the code and pick one of these sources:
| Source | What the code receives |
|---|---|
| Connected Value | One field from the record’s connected records. One connected record gives a single value; several give a list. From child records, at most the newest 100 are used and the step log says so. |
| Action Response Value from an Aggregate step | The output you set up, for example a List of values arrives as a list. |
| Action Response Value from an Export to JSON step | The exported records arrive as a list of objects. |
| Custom Value with comma-separated text | A single text value. Split it yourself (see below). |
Because a Connected Value is a single value when only one record is connected, wrap it with toList before treating it as a list:
// One value, several values or nothing -> always a list
const toList = v => Array.isArray(v) ? v : (v === null || v === undefined || v === "" ? [] : [v]); The snippets that say "Uses: toList" need this line at the top of the code.
Turn comma-separated text into a clean list #
Trims each item, makes it lowercase, drops blanks and removes duplicates.
// Input: tags "red, Blue ,red,,green" -> ["red", "blue", "green"]
const tags = String($tags ?? "")
.split(",")
.map(t => t.trim().toLowerCase())
.filter(Boolean);
returnData("tags", [...new Set(tags)]);
returnData("tag_count", new Set(tags).size); Remove duplicates from a list #
// Input: emails (a Connected Value, so one value or a list)
// Uses: toList
const emails = toList($emails).map(e => String(e).trim().toLowerCase()).filter(Boolean);
const unique = [...new Set(emails)];
returnData("emails", unique);
returnData("emails_text", unique.join(", ")); Pick a random item #
Math.random is fine for picking a message or a sample. Do not use it for passwords or security tokens.
// Input: options (a list, or comma-separated text)
// Uses: toList
const options = Array.isArray($options) ? $options : String($options ?? "").split(",").map(s => s.trim()).filter(Boolean);
returnData("picked", options.length ? options[Math.floor(Math.random() * options.length)] : null); Top items by a number #
// Inputs: customers (a list of objects, for example Export to JSON records), limit
// Change "lifetime_value" and "name" to the keys your objects use.
// Uses: toList
const top = toList($customers)
.slice()
.sort((a, b) => (Number(b.lifetime_value) || 0) - (Number(a.lifetime_value) || 0))
.slice(0, Number($limit) || 5);
returnData("top_customers", top);
returnData("top_names", top.map(c => c.name).join(", ")); Split a list into batches #
// Input: items (a list) Splits it into batches of 100
// Uses: toList
const items = toList($items);
const batches = [];
for (let i = 0; i < items.length; i += 100) batches.push(items.slice(i, i + 100));
returnData("batch_count", batches.length);
returnData("first_batch", batches[0] || []); Merge two lists and drop duplicates by id #
// Inputs: list_a, list_b (lists of objects that each have an id)
// Uses: toList
const seen = new Set();
const merged = [];
for (const item of [...toList($list_a), ...toList($list_b)]) {
if (!item || !item.id || seen.has(item.id)) continue;
seen.add(item.id);
merged.push(item);
}
returnData("merged", merged);
returnData("count", merged.length); Turn a list of objects into CSV text #
To make a CSV file from table records, the Export to CSV action does this without code.
// Input: rows (a list of objects; the first object's keys become the columns)
// Uses: toList
const rows = toList($rows);
const cols = rows.length ? Object.keys(rows[0]) : [];
const cell = v => {
const s = String(v ?? "");
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
const lines = [cols.join(","), ...rows.map(r => cols.map(c => cell(r[c])).join(","))];
returnData("csv", rows.length ? lines.join("\n") : "");
returnData("row_count", rows.length); Find what is in one list but not the other #
// Inputs: a, b (lists)
// Uses: toList
const a = toList($a).map(String);
const b = toList($b).map(String);
const onlyInA = a.filter(x => !b.includes(x));
const onlyInB = b.filter(x => !a.includes(x));
returnData("only_in_a", onlyInA);
returnData("only_in_b", onlyInB);
returnData("identical", onlyInA.length === 0 && onlyInB.length === 0); Shuffle a list and pick winners #
// Input: entries (a list) Picks 3 different winners at random
// Uses: toList
const pool = toList($entries).slice();
for (let i = pool.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[pool[i], pool[j]] = [pool[j], pool[i]];
}
returnData("winners", pool.slice(0, 3)); Was this page helpful?
Something wrong or missing on this page? Tell us.