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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read