Deduplicate Arrays by Key Keeping First Item

Remove duplicate objects from an array using a key function or property name, preserving original order and first occurrences.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
export function uniqueBy(items, keyFn) {
  if (!Array.isArray(items)) throw new TypeError("items must be an array");
  if (typeof keyFn !== "function") throw new TypeError("keyFn must be a function");
  const seen = new Set();
  const result = [];
  for (const item of items) {
    const key = keyFn(item);
    if (seen.has(key)) continue;
    seen.add(key);
    result.push(item);
  }
  return result;
}

export function uniqueByProperty(items, property) {
  if (typeof property !== "string" || property.length === 0) {
    throw new TypeError("property must be a non-empty string");
  }
  return uniqueBy(items, (item) => {
    if (item === null || typeof item !== "object") {
      throw new TypeError("items must contain objects");
    }
    return item[property];
  });
}

What the code does

Deduplicate Arrays by Key Keeping First Item keeps everything in the functions uniqueBy and uniqueByProperty.

Iteration happens inside for (const item of items) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Points of care

  • The guard typeof keyFn !== "function" short-circuits the flow with an early throw when its condition holds.

Using it

Entry signature: export function uniqueBy(items, keyFn)

Import uniqueBy from the file and call it — the rest of the code is implementation detail.

Key statements

return uniqueBy(items, (item) => {
  if (item === null || typeof item !== "object") {
    throw new TypeError("items must contain objects");
  }
  return item[property];
});
if (typeof keyFn !== "function") throw new TypeError("keyFn must be a function");
if (!Array.isArray(items)) throw new TypeError("items must be an array");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
The code throws `TypeError` — the guard `typeof keyFn !== "function"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `uniqueBy`, `uniqueByProperty` at load time.