How to Convert an Array into a Set in JavaScript – Definitive Guide

There are different methods to convert an Array into a Set in JavaScript.

Answer: const numSet = new Set(numArray);

This tutorial teaches the different methods to convert an Array into a Set in JavaScript and the appropriate use cases for each method.

Convert an Array into a Set Using Set Constructor

The set() constructor creates a Set object that stores unique values.

  • To convert a JavaScript array into a Set, you can pass the Set() constructor.
  • All the unique elements in the Array will be added to the Set.

Use this method when you want to add all the unique elements in the Array into a Set.

Code

The following code demonstrates how to convert an Array into a Set and print the elements in the Set using the spread operator.

const numArray = [1, 1, 2, 3, 3, 4];

const numSet = new Set(numArray);

console.log(...numSet);

Output

1, 2, 3, 4

Convert an Array into a Set Using For Each and Set.Add() Method

The forEach() method executes a callback function on each element in the array.

To convert an Array into a Set using the forEach() method,

  • Create a new Set object using new Set()
  • Iterate over each element using forEach()
  • During each iteration, add the element to the Set using the add() method.
  • Optionally, you can define conditions using if to add the elements to the conditionally

Use this method when you want to add elements from an Array into a Set conditionally. For example, add only even numbers to the set or check if the element is a number before adding it to the Set.

Code

The following code demonstrates how to add only the unique even numbers from the Array into the Set.

const numArray = [1, 1, 2, 3, 3, 4, 4, 4];

let evenNumSet = new Set();

numArray.forEach(function(e) {
  if (e % 2 === 0) {
    evenNumSet.add(e);
  }
});

console.log(...evenNumSet.values());

Output

2, 4

Convert Array of Objects to Set

In some cases, the array might contain JavaScript object types instead of primitive types.

This section teaches you how to add a specific object attribute from the Array into a Set.

  • Iterate over the array objects using the map() method and return the object’s property. For example, the id of each object.
  • Add the results from the map() into the Set constructor

While adding elements to Set, duplicate items will be ignored. Hence, be cautious that the object’s property doesn’t contain duplicates.

Code

let objArray = [{
    id: 1001,
    name: "Bob"
  },
  {
    id: 1002,
    name: "Ram"
  },
  {
    id: 1003,
    name: "Peter"
  }
];

const idSet = new Set(objArray.map(obj => obj.id));

console.log(...idSet);

Output

1001, 1002, 1003

Additional Resources

Leave a Comment