facu.azcue.dev logo

How to Create an Array of Unique Objects in TypeScript

Remove duplicate objects based on a specific property using a clean and reusable approach

If you ever need to create an array of unique objects based on one of their properties, this simple TypeScript snippet might come in handy.

Original array - with duplicate elements

Let’s say we have an array of products with the following structure:

<typescript>
1type Product = {
2 id: number
3 name: string
4 slug: string
5}
6
7const products: Product[] = [
8 { id: 1, name: 'Bread', slug: 'bread' },
9 { id: 2, name: 'Milk', slug: 'milk' },
10 { id: 3, name: 'Bread 2', slug: 'bread' }
11]

As you can see, the first and third products share the same slug. So if we try to display them, we’ll end up with a duplicate:

<typescript>
1products.map((product) => {
2 return (
3 <a key={product.id} href={product.slug}>{product.name}</a>
4 )
5})
6
7/* Output:
8 <a href="bread">Bread</a>
9 <a href="milk">Milk</a>
10 <a href="bread">Bread 2</a> <<< DUPLICATED
11*/

Using filter alone won’t be enough here, because it doesn't allow us to track previously seen values efficiently. That’s where a Set becomes useful.

Why use a Set?

A Set is a built-in JavaScript object that stores unique values. You can use it to keep track of which values you’ve already encountered while looping through your array. Since checking if a value exists in a Set is very fast (constant time), it's perfect for deduplication tasks like this one.

The solution

We’ll write a helper function that receives:

  • The array of objects
  • The property name we want to filter by (like "slug")

It will return a new array where only the first occurrence of each unique value is kept.

<typescript>
1const getUniquesProducts = (products: Product[], filterBy: string): Product[] => {
2 const seen = new Set<string>()
3 const uniques: Product[] = []
4
5 for (const product of products) {
6 if (!seen.has(product[filterBy])) {
7 uniques.push({
8 id: uniques.length + 1,
9 name: product.name,
10 slug: product.slug
11 })
12
13 seen.add(product.slug)
14 }
15 }
16
17 return uniques
18}

Final result

After calling the function, you’ll get a clean list of products, with no duplicate slugs:

<typescript>
1const uniquesProducts = getUniquesProducts(products, 'slug')

And rendering them:

<typescript>
1/* Output:
2 <a href="bread">Bread</a>
3 <a href="milk">Milk</a>
4*/

This approach is flexible — you can reuse the same function for any array of objects and filter by any property you need (as long as it’s a string). It's a simple, reusable way to handle deduplication in your frontend or backend logic.

tags:TypeScript