JavaScript sets resemble arrays in the sense that they are also collections of values. But, unlike arrays, these data collections can only include unique values. In other words, you can’t have duplicates in a set.
The second difference between arrays and sets is that inside sets, the values are stored in no particular order, so you can just call them by their name.
let events = new Set()
let event1 = { type: "concert", day: "Saturday" }
let event2 = { type: "book launch", day: "Sunday" }
let event3 = { type: "conference", day: "Monday" }
let event4 = { type: "meetup", day: "Tuesday" }
let event5 = { type: "football match", day: "Friday" }
events.add(event1)
events.add(event2)
events.add(event3)
events.add(event4)
for (let item of events.values()) {
console.log(item)
}
If you want to check whether a specific value is found inside the set, you can use the has(value) method. To delete an item, you can use the delete(value) method.
console.log(events.has(event5)) // false
console.log(events.has(event2)) // true
Explanation
Other useful methods available for sets include clear() and size(). The former removes all the items from the set, while the latter returns the number of elements in the set.
We’ve established that this type of collection can only contain unique values. What happens if we want to add an event twice?
let cities = new Set();
let city1 = { name: "London" };
let city2 = { name: "Barcelona"};
let city3 = { name: "Milan"};
cities.add(city1);
cities.add(city2);
cities.add(city1);
cities.add(city3);
cities.forEach((city, cities) => {
console.log(city);
});
// { name: 'London' }
// { name: 'Barcelona' }
// { name: 'Milan' }
This will list the names of the three cities, each of them only once.
Converting sets to arrays and vice versa is easy to do and very handy if you want to perform operations such as filtering and returning the unique values from a data collection.
Here’s how to turn a set into an array
let set = new Set([9, 15, "a string", {"objectKey": "objectValue"}]);
set.add(true);
let arr = [...set]; // destructuring
console.log(arr); fj
// Outputs [9, 15, "a string", {objectKey: "objectValue"}, true]
Here’s how to convert an array to a set
let arr2 = [9, 15, "a string", {"objectKey": "objectValue"}];
let arr2converted = [...new Set(arr2)];
console.log(arr2converted);
// Outputs [9, 15, "a string", {objectKey: "objectValue"}, true]
let users = ["John", "Murray", "Jane", "Jane", "Anne"];
// Method 1
function unique(users) {
return Array.from(new Set(users));
}
console.log(unique(users));
// Method 2
let set = new Set(users);
let arrFromSet = [...set];
console.log(arrFromSet);
Finally, let’s say we want to add all the users from above to a new set and a new array. Let’s see which collection performs the operation faster.
let arr = [];
let set = new Set();
let users = ["John", "Murray", "Jane", "Jane", "Anne", "John", "Murray", "Jane", "Jane", "Anne"];
for (let i = 0; i < users.length; i++) {
arr.push(users[i]);
set.add(users[i]);
}
let results;
console.time('Array');
results = arr.indexOf("Anne") !== -1;
console.timeEnd('Array');
console.time('Set');
results = set.has("Anne");
console.timeEnd('Set');
// Array: 0.052ms
// Set: 0.005ms