The Data Wrangler
All guides

Make a JavaScript lookup join reject duplicate keys

Build a checked Map for a one-to-many lookup, retain unmatched rows and catch a duplicate dimension key before it can overwrite another value.

Abstract diagram for make a javascript lookup join reject duplicate keys
Editorial diagram. The forms and marks are illustrative.

A tiny enrichment job adds the customer’s region to each order. The output has the same number of orders as the input, and the totals still add up. Then a region starts changing between runs. A likely cause is that two customer records carry the same key, and the index kept whichever appeared last. No extra order row is needed for the join to be wrong.

Make the lookup enforce the relationship

Orders can repeat a customer ID. The customer table in this example has to contain at most one row per ID. JavaScript’s Map.set updates an existing entry with the same key, which makes it useful for replacement and silent about unexpected duplicates. Check first so the index construction enforces the input contract.

const customers = [{ id: 'C07', region: 'West' }];
const orders = [
  { order: 'A1', customer: 'C07' },
  { order: 'A2', customer: 'C07' },
  { order: 'A3', customer: 'C99' }
];

const byCustomer = new Map();
for (const customer of customers) {
  if (byCustomer.has(customer.id)) {
    throw new Error('Duplicate customer: ' + customer.id);
  }
  byCustomer.set(customer.id, customer);
}
const enriched = orders.map(row => {
  const customer = byCustomer.get(row.customer);
  return {
    ...row,
    region: customer?.region ?? null,
    matched: customer !== undefined
  };
});
console.log(enriched.map(row => [row.order, row.region, row.matched]));

This example prints West for A1 and A2, and a null region with false for A3. Add a second customer with ID C07 above the loop. The index now stops before writing the report. A matched customer can also lack a region, which is why the explicit matched flag is separate from the region value.

Check the key before changing the join

Identifier columns should have a consistent type. A numeric 7, the string '7' and the string '007' can represent different keys under the source contract. Decide how the source defines them, and validate both tables accordingly. If repeated customer rows are legitimate historical versions, the missing information may be the effective date. An order-preserving Map is no substitute for deciding which version applied at the time of the order.