Convert a Set to an Array in TypeScript

avatar

Borislav Hadzhiev

Tue Feb 15 20222 min read

banner

Photo by Brooke Cagle

Convert a Set to an Array in TypeScript #

Use the Array.from() method to convert a Set to an array, e.g. const arr = Array.from(set). The Array.from method creates a new array from an iterable object, such as a Set and returns the result.

index.ts
const set1: Set<string> = new Set(['one', 'two', 'three']); // 👇️ const arr: string[] const arr = Array.from(set1); // 👇️ ['one', 'two', 'three'] console.log(arr);

The only parameter we passed to the Array.from method is an iterable object (a Set in the example).

The method converts the iterable object into an array and returns a new array instance.

This is the recommended approach when using TypeScript because the compiler often complains when using the spread operator (...) with iterators.

An alternative approach is to use the spread operator (...).

index.ts
const set1: Set<string> = new Set(['one', 'two', 'three']); // 👇️ const arr: string[] const arr = [...set1]; // 👇️ ['one', 'two', 'three'] console.log(arr);

The spread operator allows us to unpack the values of the Set into the array.

You could also use this approach to convert multiple Set objects into an array.

index.ts
const set1: Set<string> = new Set(['one', 'two', 'three']); const set2: Set<string> = new Set(['four', 'five', 'six']); // 👇️ const arr: string[] const arr = [...set1, ...set2]; // 👇️ ['one', 'two', 'three', 'four', 'five', 'six'] console.log(arr);

The order in which you unpack the Set objects into the array is preserved.

An alternative and more manual approach is to use the forEach() method to iterate over the Set and on each iteration push the element into the array.

index.ts
const set1: Set<string> = new Set(['one', 'two', 'three']); const arr: string[] = []; set1.forEach((element) => { arr.push(element); }); // 👇️ ['one', 'two', 'three'] console.log(arr);

The function we passed to the Set.forEach method gets called with each value in the Set.

On each iteration we simply push the value into the array.

This is definitely the most verbose and manual of the 3 approaches. I prefer either of the other 2 ways to convert a Set into an array.
Use the search field on my Home Page to filter through my more than 1,000 articles.