Sometimes, we want to convert a JavaScript array into a set.
In this article, we’ll look at how to convert a JavaScript array to a set.
Create a Set with the JavaScript Set Constructor
We can use the JavaScript Set
constructor to create a JavaScript set from an array.
For instance, we can write:
const array = [{
name: "malcom",
dogType: "golden retriever"
},
{
name: "peabody",
dogType: "bulldog"
},
{
name: "pablo",
dogType: "chihuahua"
}
];
const namesSet = new Set(array.map(d => d.name));
console.log(namesSet)
We have an array
array with an array of objects.
We want to create a set with the name
value from each object.
To do this, we call array.map
with a callback to return the name
property of each object.
We then pass the returned names string array into the Set
constructor to create the set.
Therefore namesSet
is a set with “malcom”
, “peabody”
, and “pablo”
in it.
Passing the array into the Set
constructor will remove the duplicate values if there are any in the set.
Conclusion
We can use the JavaScript Set
constructor to create a set from an array.