How to Convert a Set to an Array in TypeScript ?
Last Updated :
15 Jan, 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]
Share your thoughts in the comments
Please Login to comment...