How to Get Distinct Values from an Array in TypeScript?

In this tutorial, I will explain how to get distinct values from an array in TypeScript efficiently using various methods with examples. As a developer, you may often encounter situations where you need to filter out duplicate values from an array and obtain only the unique elements.

The Problem: Duplicate Values in a TypeScript Array

Imagine you’re working on a project for a client in New York City. You have an array of customer names, but you notice that some names appear multiple times due to data inconsistencies. To generate accurate reports and perform further analysis, you need to extract only the distinct names from the array.

Here’s an example of a TypeScript array with duplicate values:

const customerNames: string[] = [
  'John Smith',
  'Emily Johnson',
  'Michael Davis',
  'John Smith',
  'Emma Brown',
  'Michael Davis',
];

Check out Check if an Array Contains a String in PowerShell

Solution 1: Using the Set Object

One of the most efficient ways to get distinct values from an array in TypeScript is by using the Set object in combination with the spread operator. The Set object allows you to store unique values of any type.

Here’s how you can use Set to get distinct values:

const customerNames: string[] = [
  'John Smith',
  'Emily Johnson',
  'Michael Davis',
  'John Smith',
  'Emma Brown',
  'Michael Davis',
];
const uniqueNames = [...new Set(customerNames)];
console.log(uniqueNames);
// Output: ['John Smith', 'Emily Johnson', 'Michael Davis', 'Emma Brown']

In this example, we create a new Set object and pass the customerNames array to its constructor. The Set object automatically removes any duplicate values. We then use the spread operator (...) to convert the Set back to an array, resulting in an array with only distinct values.

Here is the exact output in the screenshot below; I executed the above TypeScript code using VS Code.

Get Distinct Values from an Array in TypeScript

Read Filter An Array with Multiple Conditions in TypeScript

Solution 2: Using the filter() Method

Another approach to get distinct values is by using the filter() method in combination with the indexOf() method in TypeScript. The filter() method creates a new array with elements that pass a certain condition, while indexOf() returns the first index at which a given element is found in an array.

Here’s an example:

const customerNames: string[] = [
  'John Smith',
  'Emily Johnson',
  'Michael Davis',
  'John Smith',
  'Emma Brown',
  'Michael Davis',
];
const uniqueNames = customerNames.filter(
  (name, index) => customerNames.indexOf(name) === index
);
console.log(uniqueNames);
// Output: ['John Smith', 'Emily Johnson', 'Michael Davis', 'Emma Brown']

In this solution, we use the filter() method to iterate over each element in the customerNames array. For each element, we check if the index of its first occurrence (indexOf(name)) matches the current index. If they match, it means it’s the first occurrence of that element, and it will be included in the resulting array.

You can see the exact output in the screenshot below:

TypeScript Get Distinct Values from an Array

Read How to Loop Through an Array in PowerShell?

Handle Objects in an Array in TypeScript

In some scenarios, you might come across arrays containing objects rather than primitive values in TypeScript. Let’s consider an example where you have an array of customer objects, and you want to get distinct customers based on their email addresses.

Here is the complete code.

interface Customer {
  name: string;
  email: string;
  country: string;
}

const customers: Customer[] = [
  { name: 'John Smith', email: 'john@example.com', country: 'USA' },
  { name: 'Emily Johnson', email: 'emily@example.com', country: 'USA' },
  { name: 'Michael Davis', email: 'michael@example.com', country: 'USA' },
  { name: 'John Smith', email: 'john@example.com', country: 'USA' },
  { name: 'Emma Brown', email: 'emma@example.com', country: 'USA' },
];

To get distinct customers based on their email addresses, you can use the filter() method along with the map() method:

const uniqueCustomers = customers.filter(
  (customer, index, self) =>
    index === self.findIndex((c) => c.email === customer.email)
);
console.log(uniqueCustomers);

In this example, we use the filter() method to iterate over each customer object. For each customer, we find the index of the first occurrence of a customer with the same email address using the findIndex() method.

If the current index matches the index of the first occurrence, it means it’s a unique customer based on the email address, and it will be included in the resulting array.

You can see the exact output in the screenshot below:

How to Get Distinct Values from an Array in TypeScript

Read Filter Empty Strings from an Array in TypeScript

Performance Considerations

When working with large arrays, performance becomes a critical factor. Here are a few things to keep in mind:

  1. The Set object approach is generally the most efficient way to get distinct values from an array. It has a time complexity of O(n), where n is the number of elements in the array.
  2. The filter() and indexOf() approach has a time complexity of O(n^2) in the worst case because it performs nested iterations. However, for smaller arrays, the performance difference might not be significant.
  3. If you’re dealing with objects in an array and need to get distinct values based on a specific property, using filter() and findIndex() is a suitable approach. It has a time complexity of O(n^2) in the worst case.

Choosing the appropriate technique is important based on your specific requirements and the size of the array you’re working with.

Conclusion

In this tutorial, I have explained different ways to get distinct values from an array in TypeScript. We covered using the Set object, the filter() method with indexOf(), and handling objects in an array. Do let me know in the comment below if you face any issues.

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App