How to Get Distinct Values from an Array in TypeScript?

Recently, while working on a Typescript project, I got a requirement to get distinct values from an array in Typescript. In this tutorial, I will explain how to extract distinct values from an array in TypeScript efficiently. There are various methods to get distinct values from an array in TypeScript.

Get Distinct Values from an Array in TypeScript

Now, let me show you how to get distinct values from an array in TypeScript using different methods.

Using the Set Object in TypeScript

The most efficient way to get unique values from an array in TypeScript is by using the Set object along with the spread operator. Here’s an example:

const cities: string[] = ['New York', 'Los Angeles', 'Chicago', 'New York', 'Houston', 'Chicago'];
const distinctCities: string[] = [...new Set(cities)];
console.log(distinctCities); // Output: ['New York', 'Los Angeles', 'Chicago', 'Houston']

In this example, we have an array cities that contains duplicate values. By creating a new Set object from the cities array and then spreading it back into a new array using the spread operator (...), we obtain an array distinctCities that contains only the unique values.

Here is the exact output in the screenshot below:

Get Distinct Values from an Array in TypeScript

Check out How to Find an Object in a TypeScript Array?

Using the filter() and indexOf() Methods

Another approach to get distinct values from an array is by using the TypeScript filter() method in combination with the indexOf() method. Here’s an example:

const names: string[] = ['John', 'Emma', 'Michael', 'Emma', 'Oliver', 'John'];
const distinctNames: string[] = names.filter((name, index) => names.indexOf(name) === index);
console.log(distinctNames); // Output: ['John', 'Emma', 'Michael', 'Oliver']

In this example, the filter() method iterates over each element of the names array. For each element, it checks if the index of the first occurrence of that element in the array is equal to the current index. If they match, it means it’s the first occurrence of that element, and it is included in the resulting distinctNames array.

Read Calculate the Sum of an Array in TypeScript

Get Distinct Values from an Array of Objects

When working with an array of objects, you may want to extract distinct values based on a specific property. TypeScript allows you to achieve this using the map() method along with the Set object. Here’s an example:

interface Person {
  id: number;
  name: string;
  age: number;
}

const people: Person[] = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 25 },
  { id: 4, name: 'Alice', age: 28 },
];

const distinctAges: number[] = [...new Set(people.map(person => person.age))];
console.log(distinctAges); // Output: [25, 30, 28]

In this example, we have an array of Person objects. To get the distinct values of the age property, we first use the map() method to extract all the age values into a new array. Then, we create a Set object from that array and spread it back into a new array, resulting in the distinctAges array containing only unique age values.

Here is the exact output in the screenshot below:

Get Distinct Values from an Array of Objects in Typescript

Read Reverse an Array in TypeScript

Define a Type for an Array with Unique Items

TypeScript’s advanced types can be used to enforce unique items in an array through type manipulation, ensuring compile-time checks for uniqueness. Here’s an example:

type UniqueArray<T> = T[] & { __uniqueArrayBrand: never };

function createUniqueArray<T>(array: T[]): UniqueArray<T> {
  return [...new Set(array)] as UniqueArray<T>;
}

const uniqueNumbers: UniqueArray<number> = createUniqueArray([1, 2, 3, 2, 4]);
console.log(uniqueNumbers); // Output: [1, 2, 3, 4]

// This will result in a compile-time error
const nonUniqueNumbers: UniqueArray<number> = [1, 2, 3, 2, 4];

In this example, we define a type UniqueArray<T> that extends the regular array type T[] and adds a unique brand property __uniqueArrayBrand of type never. This ensures that only arrays created through the createUniqueArray function can be assigned to variables of type UniqueArray<T>. The createUniqueArray function takes an array and returns a new array with unique values using the Set object.

Conclusion

In this tutorial, we saw various ways to get distinct values from an array in TypeScript. Whether you have an array of primitive values or an array of objects, TypeScript provides efficient methods to extract unique values. By using the Set object, the filter() and indexOf() methods, or leveraging TypeScript’s advanced types, you can ensure that your arrays contain only distinct values.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.