How to Convert a Set to an Array in TypeScript ?
Last Updated :
17 Jul, 2024
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into arrays that accept duplicate values as well.
These are the following methods to convert a set to an Array:
Using the Array.from() method
The Array.from() method returns an array from an entity that has the length property and is iterable. As Set is an iterable entity, we can use this method to convert it into an array.
Syntax:
const newArrayName = Array.from(setName);
Example: The below code example explains the use of the Array.from() method to convert a Set into an array.
JavaScript
const testSet = new Set<number>();
for (let i = 1; i <= 5; i++) {
testSet.add(i);
}
console.log(testSet);
const arrayFromSet: number[] = Array.from(testSet);
console.log(arrayFromSet);
arrayFromSet[5] = 5;
console.log(arrayFromSet);
Output:
Set (5) {1, 2, 3, 4, 5}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 5]
Using the spread operator
The spread operator can also be used to convert a Set into an array using the three dots(...) syntax followed by the name of the Set.
Syntax:
const newArrayName = [...setName];
Example: The below code example implements the spread operator to convert a set to an array in TypeScript.
JavaScript
const testSet = new Set<number>();
for (let i = 1; i <= 5; i++) {
testSet.add(i);
}
console.log(testSet);
const arrayFromSet: number[] = [...testSet];
console.log(arrayFromSet);
arrayFromSet[5] = 5;
console.log(arrayFromSet);
Output:
Set (5) {1, 2, 3, 4, 5}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 5]
Using the forEach() iterator method
We can use the forEach() loop to iterate through all the elements of the Set and then push each one of them into an array using the Array.push() method.
Syntax:
setName.forEach((val)=>{
arrayName.push(val);
});
Example: The below code example converts a Set into an array in TypeScript using forEach() loop method.
JavaScript
const testSet = new Set<number>();
for (let i = 1; i <= 5; i++) {
testSet.add(i);
}
console.log(testSet);
const arrayFromSet: number[] = [];
testSet.forEach((setVal) => {
arrayFromSet.push(setVal);
});
console.log(arrayFromSet);
arrayFromSet[5] = 5;
console.log(arrayFromSet);
Output:
Set (5) {1, 2, 3, 4, 5}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 5]
Using a custom conversion function
We can define a custom function that iterates over the Set and manually adds each element to an array.
Example: In this example we defines a function setToArray to convert a Set to an Array by iterating over the Set and pushing its elements into an array. It then demonstrates this conversion with logging.
JavaScript
// Define a function to convert a Set to an Array
function setToArray<T>(set: Set<T>): T[] {
const array: T[] = [];
set.forEach(value => array.push(value));
return array;
}
// Define a Set
const testSet = new Set<number>();
for (let i = 1; i <= 5; i++) {
testSet.add(i);
}
console.log("Set:", testSet);
// Convert Set to Array using the custom function
const arrayFromSet: number[] = setToArray(testSet);
console.log("Array from Set:", arrayFromSet);
Output:
"Set:", Set (5) {1, 2, 3, 4, 5}
"Array from Set:", [1, 2, 3, 4, 5]
Using the Array.concat() Method
Another approach to convert a Set into an array in TypeScript, while ensuring simplicity and clarity, is using the Array.concat() method. This method can effectively take an empty array and concatenate it with the elements of the Set, producing an array as a result.
Example: The Array.concat() method is typically used to merge two or more arrays into one. However, by combining it with the spread operator within the argument, you can use it to convert a Set into an array. This method ensures that the original set remains unchanged while producing a new array containing all elements of the Set.
JavaScript
// Initialize a Set with some values
const setName = new Set([1, 2, 3, 4, 5]);
// Convert Set to Array using Array.concat() and spread operator
const newArrayName = [].concat(...setName);
// Output the results
console.log("Set:", setName);
console.log("Array from Set:", newArrayName);
OutputSet: Set(5) { 1, 2, 3, 4, 5 }
Array from Set: [ 1, 2, 3, 4, 5 ]
Using the reduce() Method
The reduce() method executes a reducer function on each element of the Set, resulting in a single output value, which in this case will be an array.
Syntax:
const newArrayName = Array.from(setName).reduce<number[]>((acc, curr) => {
acc.push(curr);
return acc;
}, []);
Example: The below code example demonstrates using the reduce() method to convert a Set into an array in TypeScript.
JavaScript
const testSet = new Set < number > ();
for (let i = 1; i <= 5; i++) {
testSet.add(i);
}
console.log(testSet);
const arrayFromSet: number[] = Array.from(testSet).reduce < number[] > ((acc, curr) => {
acc.push(curr);
return acc;
}, []);
console.log(arrayFromSet);
arrayFromSet[5] = 5;
console.log(arrayFromSet);
Output:
Set (5) {1, 2, 3, 4, 5}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 5]
This method not only converts the Set into an array but does so in a way that's easily readable and understandable, making it an excellent choice for scenarios where clarity is as important as functionality.
Similar Reads
How to Convert a Dictionary to an Array in TypeScript ?
In TypeScript, converting a dictionary(an object) into an Array can be useful in scenarios where you need to work with the values in a more iterable and flexible manner. These are the following approaches: Table of Content Using Object.keys methodUsing Object.values methodUsing Object.entries method
3 min read
How to Clone an Array in TypeScript ?
A cloned array is an array that contains all the items or elements contained by an already existing array in the same order. A cloned array does not affect the original array. If there is any change made in the cloned array it will not change that item in the original array. We can use the following
5 min read
How to Convert an Array of Objects into Object in TypeScript ?
Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript.We are given an array of objects a
3 min read
How to Sort an Array in TypeScript ?
Array sorting is the process of arranging the elements within an array in a specified order, often either ascending or descending based on predetermined criteria. Below are the approaches used to sort an array in typescript: Table of Content Method 1: Using sort methodMethod 2: Spread OperatorMethod
3 min read
How to Convert a String to enum in TypeScript?
In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript.These are the two approaches that can be used to solve it:Table of ContentUsi
5 min read
How to Create a Stack in TypeScript using an Array ?
Stack is a linear Data Structure that is based on the LIFO concept (last in first out). There are 5 primary operations in the stack as follows:push method(): This method adds element x to the stack.pop() Method: This method removes the last element of the stack.peek() Method: This method returns the
3 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do.Table of ContentUsing JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsing
5 min read
How to Convert Map to JSON in TypeScript ?
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion.Table of ContentUsing JSON.stringifyUsing fast-json-st
5 min read
How to Convert String to JSON in TypeScript ?
Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript:Table of ContentConvert String to JSON Using JSON.parse()Convert String to
5 min read
How to Define a Generic Type for an Array in TypeScript ?
Generics in TypeScript are a way to write reusable code that can work with different types of data. When it comes to defining generic types for arrays. TypeScript provides flexible options to ensure type safety while allowing for flexibility in the types of elements stored in the array.Table of Cont
3 min read