How to Convert an Array to a Set in JavaScript


When working with arrays in JavaScript, you might find yourself needing to eliminate duplicate values or use the unique elements property of a Set. In this guide, we’ll explore how to convert an array to a Set, handle arrays of objects, and even add new values to an existing Set.


Convert an Array to Set in JavaScript

You can easily convert an array to a Set in JavaScript using the Set constructor. When you pass an array to the Set constructor, it automatically eliminates duplicate values, making it a quick solution for creating a Set from an array.

JavaScript
const array = [1, 2, 3, 1, 2, 4];
const setFromArr = new Set(array);

console.log(setFromArr); // Output: Set { 1, 2, 3, 4 }

The resulting Set, setFromArr, contains only unique values from the original array.

Convert an Array of Objects to a Set

If your array contains objects, you can use various approaches to convert it to a Set:

Using Array.map()

By applying JSON.stringify during the mapping, we create a Set based on the serialized objects, ensuring uniqueness.

JavaScript
const arrayOfObjects = [{ id: 1 }, { id: 2 }, { id: 1 }];

const setFromArrOfObjects = new Set(arrayOfObjects.map(JSON.stringify));

console.log(setFromArrOfObjects); 
// Output: Set { '{"id":1}', '{"id":2}' }

Using Array.forEach()

This method allows you to process values before adding them to the Set.

JavaScript
const setFromArrOfObjects = new Set();

arrayOfObjects.forEach(element => {
  setFromArrOfObjects.add(element);
});

console.log(setFromArrOfObjects); 
// Output: Set { { id: 1 }, { id: 2 } }

Using Array.reduce()

This method is used to iterate over the array of objects. The add method is called on the Set for each unique value. Allows you to accumulate unique values into the Set.

JavaScript
const arrayOfObjects = [{ id: 1 }, { id: 2 }, { id: 1 }];
const idSet = arrayOfObjects.reduce((set, obj) => {
  set.add(obj.id);
  return set;
}, new Set());
console.log(idSet);
// Output: Set { 1, 2 }

Add Array of Values to an Existing Set

Using Spread Syntax

Set objects and arrays are iterable, allowing us to use the spread syntax to unpack them into a new Set.

JavaScript
const existingSet = new Set([1, 2, 3]);
const newArray = [3, 4, 5];
const combinedSet = new Set([...existingSet, ...newArray]);
console.log(combinedSet);
// Output: Set { 1, 2, 3, 4, 5 }

Using for…of Loop

A for…of loop can also be employed to iterate over the values in the array and add them to the existing Set.

JavaScript
const existingSet = new Set([1, 2, 3]);
const newArray = [3, 4, 5];
for (const value of newArray) {
  existingSet.add(value);
}
console.log(existingSet);
// Output: Set { 1, 2, 3, 4, 5 }

🧪Practice Coding Problem: Convert Array to Set

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You are given an array of numbers. Write a function to convert the array into a Set and return the resulting Set.

JavaScript
/**
 * Convert an array to a Set
 * @param {Array} arr - The input array.
 * @returns {Set} - The Set containing unique values from the array.
 */
function convertArrayToSet(arr) {
  // > > > 👉 Write code here 👈 < < <
}

// Example
const inputArray = [1, 2, 2, 3, 4, 4, 5];
const result = convertArrayToSet(inputArray);
console.log(result); 
// Expected Output: Set { 1, 2, 3, 4, 5 }
Please attempt before seeing the Answer:
JavaScript
function convertArrayToSet(arr) {
  return new Set(arr);
}

In this solution, we use the Set constructor directly with the input array. The constructor automatically eliminates duplicate values, creating a Set with unique elements.


Hopefully,, you are all Set on you path converting between these data structures. Like always, keep coding! 🚀

Scroll to Top