DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

How to Remove Duplicates from an Array in TypeScript

Use a Set to deduplicate primitive values in TypeScript while preserving first-seen order. For records, define duplicates by a key such as an ID.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an array of primitive values, convert it to a Set and back: const unique = [...new Set(values)];. This returns a new array containing the first occurrence of each value, in its original order. For objects, choose the field or rule that defines a duplicate; a Set does not compare object contents.

Remove duplicate primitive values with a Set

For strings, numbers, booleans, and other primitive values, JavaScript’s built-in Set is the simplest default:

As an Amazon Associate I earn from qualifying purchases.

const values = ["a", "b", "a", "c"];
const unique = [...new Set(values)];

console.log(unique); // ["a", "b", "c"]

Array.from(new Set(values)) produces the same result. Both forms create a new array; they do not sort, splice, or otherwise modify the input. A Set iterates in insertion order, so the result keeps the first occurrence of each distinct value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What counts as a duplicate?

A Set uses SameValueZero equality. For ordinary primitive values, this works like ===, with two notable details: NaN is considered equal to itself, and positive and negative zero are considered equal. Thus, multiple NaN values collapse to one.

Objects and arrays are different: a Set compares them by reference, not by their contents. Two separately created objects such as { id: 1 } are distinct entries, even though their fields match. If records are duplicates because they share an ID or another field, deduplicate using that field.

Deduplicate records by a field

This function keeps the first record encountered for each ID and preserves the order of those retained records:

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
function uniqueById<T extends { id: string | number }>(items: T[]): T[] {
  const seen = new Set<string | number>();
  const result: T[] = [];

  for (const item of items) {
    if (seen.has(item.id)) continue;
    seen.add(item.id);
    result.push(item);
  }

  return result;
}

Change the field and key type to match your records. The code makes the policy explicit: the first item for an ID wins. If you need the last record instead, use an explicit update strategy, such as a Map keyed by ID, and decide whether the output should follow first-seen key order or the order of the last occurrences.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When another approach makes sense

Filter with indexOf

A familiar primitive-array idiom is values.filter((value, index) => values.indexOf(value) === index). It does not handle NaN the same way as a Set: indexOf(NaN) cannot find a matching value. Prefer Set unless you specifically need different equality behavior.

Use a custom comparer

If duplicates are defined by a custom comparison rule, or you need sorted output, sort and then remove adjacent duplicates with a comparer. TypeScript’s 4.3 release notes show a comparer-based makeUnique example that uses sort and splice; those operations mutate the array. To preserve the original input, sort a copy first, for example with const sorted = [...items].sort(compare), and deduplicate that copy.

TypeScript configuration and runtime support

Deduplication with Set is JavaScript runtime behavior; TypeScript provides the static types. If the compiler reports an unknown Set type or an iterable/spread error, check the project’s TypeScript version and target and lib settings, as well as the JavaScript runtime that executes the code. Do not assume every project configuration supports the same syntax or built-in declarations.

MDN describes Set as widely available across browsers since July 2015. That browser-availability statement does not by itself establish support in every runtime or guarantee that a project’s TypeScript configuration includes the necessary declarations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance: what can and cannot be concluded

MDN says a Set’s has check is, on average, quicker than checking most previously added values with Array.prototype.includes when both collections have the same size. The JavaScript specification requires average access times to be sublinear, but this is not a benchmark for every deduplication workload and does not establish a universal speedup. Choose the approach for its equality and ordering behavior first, and measure your own workload if performance is the deciding factor.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.