Skip to content

CSV Diff — JavaScript source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// csv-diff — key-based row diff of two RFC-4180 CSVs. JavaScript port (canonical TS:
// src/lib/csv-diff.ts; Go twin: cli/csv-diff). Shared-parser semantics: quoted
// cells (embedded commas, quotes, newlines), CR dropped, a trailing field without
// a newline still completes its row, and blank single-cell rows dropped as
// trailing noise. Strict per-side validation — empty CSV, duplicate columns,
// ragged rows ("Left: row 2 has 3 cells, expected 4") — then a key-based diff
// over the sorted key union: added/removed rows and changed rows whose differing
// column names come out sorted. Never throws; errors travel as strings.
'use strict';

function csvToRows(csv) {
  const rows = [];
  let field = '';
  let row = [];
  let inQ = false;
  for (let i = 0; i < csv.length; i++) {
    const ch = csv[i];
    if (inQ) {
      if (ch === '"') {
        if (csv[i + 1] === '"') { field += '"'; i++; } else inQ = false;
      } else field += ch;
    } else if (ch === '"') inQ = true;
    else if (ch === ',') { row.push(field); field = ''; }
    else if (ch === '\n') { row.push(field); rows.push(row); row = []; field = ''; }
    else if (ch !== '\r') field += ch;
  }
  if (field.length > 0 || row.length > 0) { row.push(field); rows.push(row); }
  return rows;
}

// Blank single-cell rows are trailing noise to a diff, not data.
function parseCsv(text) {
  return csvToRows(text).filter((r) => !(r.length === 1 && r[0] === ''));
}

// Strict per-side validation; throws with the pinned error strings.
function toRecords(rows, label) {
  if (rows.length === 0) throw new Error(`${label}: empty CSV`);
  const header = rows[0];
  const seen = new Set();
  for (const name of header) {
    if (seen.has(name)) throw new Error(`${label}: duplicate column "${name}"`);
    seen.add(name);
  }
  const records = [];
  for (let r = 1; r < rows.length; r++) {
    if (rows[r].length !== header.length)
      throw new Error(`${label}: row ${r + 1} has ${rows[r].length} cells, expected ${header.length}`);
    const record = {};
    header.forEach((name, c) => { record[name] = rows[r][c]; });
    records.push(record);
  }
  return { header, records };
}

// Diff two CSVs by key column (default: the first header column).
function csvDiff(leftRaw, rightRaw, keyColumn) {
  if (!leftRaw.trim() || !rightRaw.trim())
    return { rows: [], same: false, error: 'Both inputs are required' };
  try {
    const left = toRecords(parseCsv(leftRaw), 'Left');
    const right = toRecords(parseCsv(rightRaw), 'Right');
    const key = keyColumn ?? left.header[0];
    if (!left.header.includes(key)) return { rows: [], same: false, error: `Left: no key column "${key}"` };
    if (!right.header.includes(key)) return { rows: [], same: false, error: `Right: no key column "${key}"` };
    if (left.header.length !== right.header.length || left.header.some((h, i) => h !== right.header[i]))
      return { rows: [], same: false,
        error: `Headers differ: left [${left.header.join(', ')}] vs right [${right.header.join(', ')}]` };
    const index = (records, label) => {
      const by = new Map();
      for (const rec of records) {
        if (by.has(rec[key])) throw new Error(`${label}: duplicate key "${rec[key]}"`);
        by.set(rec[key], rec);
      }
      return by;
    };
    const leftBy = index(left.records, 'Left');
    const rightBy = index(right.records, 'Right');
    const rows = [];
    for (const k of [...new Set([...leftBy.keys(), ...rightBy.keys()])].sort()) {
      const l = leftBy.get(k);
      const r = rightBy.get(k);
      if (!l) rows.push({ key: k, type: 'added', after: r });
      else if (!r) rows.push({ key: k, type: 'removed', before: l });
      else {
        const columns = left.header.filter((n) => n !== key && l[n] !== r[n]).sort();
        if (columns.length > 0) rows.push({ key: k, type: 'changed', columns, before: l, after: r });
      }
    }
    return { rows, same: rows.length === 0, error: null };
  } catch (e) {
    return { rows: [], same: false, error: e.message };
  }
}

// Example:
// csvDiff('id,name\n1,Ada\n2,Bob', 'id,name\n1,Ada\n2,Robert\n3,New').rows
// → [{ key: '2', type: 'changed', columns: ['name'], before: {…}, after: {…} },
//    { key: '3', type: 'added', after: { id: '3', name: 'New' } }]

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →