How to Convert a Set to an Array in JavaScript

Convert a Set to an Array in JavaScript

JavaScript offers a powerful built-in Set object that stores unique values. While Sets are useful for ensuring uniqueness, there are many cases where working with arrays is more practical—such as mapping, filtering, or looping through indexed elements.

So, how do you convert a Set back into an array? In this tutorial, we’ll explore beginner-friendly and modern ways to do exactly that. Whether you're cleaning up duplicates or transforming datasets, knowing how to convert a Set to an Array is essential for any JavaScript developer.

Method 1: Using the Spread Operator ([...set])

This is the most modern and concise way to convert a Set into an array. The spread operator unpacks all values from the Set into a new array.

const fruitSet = new Set(["apple", "banana", "cherry"]);
const fruitArray = [...fruitSet];
console.log(fruitArray);
["apple", "banana", "cherry"]

Method 2: Using Array.from()

The Array.from() method is another clean and readable way to turn a Set into an array. This method creates a shallow-copied array from any iterable object—like a Set.

const colorSet = new Set(["red", "blue", "green"]);
const colorArray = Array.from(colorSet);
console.log(colorArray);
["red", "blue", "green"]

Method 3: Using a for...of Loop

If you're working in older environments or want full control over how items are added, you can use a for...of loop to manually build an array from a Set.

const itemSet = new Set(["Item 1", "Item 2", "Item 3"]);
const itemArray = [];

for (const item of itemSet) {
  itemArray.push(item);
}

console.log(itemArray);
["Item 1", "Item 2", "Item 3"]

Why Convert a Set to an Array?

Although Sets ensure uniqueness, arrays offer more tools and flexibility. You might want to:

  • Access items by index (e.g., array[0])
  • Use array methods like map(), filter(), reduce()
  • Sort the values
  • Work with external libraries expecting arrays

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...