Sets are a new object type which allow to create collections of unique values. The values in a set can be either primitives like strings or integers and non-primitives like object literals or arrays.
const set = new Set([10, 10, 20, 30, 'Tom', {name: 'Mike'}]);
console.log(set);
Output:
Set(5) {10, 20, 30, "Tom", {name: 'Mike'}}
Append new element with a specified value at the end of the Set object and return Set object
const set = new Set();
set.add(10);
set.add(10);
set.add(20);
set.add(30);
set.add('Tom');
set.add({name: 'Mike'});
console.log(set);
Output:
Set(5) {10, 20, 30, "Tom", {name: 'Mike'}}
It returns the number of elements in the Set.
const set = new Set([10, 10, 20, 30, 30, 40, 'Tom', {name: 'Mike'}]);
console.log(set.size); // Output: 6
It deletes an element with the specified value from the Set object
const set = new Set();
set.add(10).add(10).add(20).add(30).add(30).add(40).add('Tom').add({name: 'Mike'});
set.delete(20);
set.delete('Tom');
console.log(set);
Output:
Set(4) {10, 30, 40, {name: 'Mike'}}
It returns true if the specified value is present in the Set object.
const set = new Set();
set.add(10).add(10).add(20).add(30).add(30).add(40).add('Tom').add({name: 'Mike'});
console.log(set.has('Tom')); // Output: true
console.log(set.has('Mike')); // Output: false
It removes all the element from the set.
const set = new Set();
set.add(10).add(10).add(20).add(30).add(30).add(40).add('Tom').add({name: 'Mike'});
set.clear();
console.log(set); // Output: Set(0) {}
It executes a provided function once for each value in the Set object, in insertion order
function logSetElements(value1, value2, set) {
console.log(`s[${value1}] = ${value2}`);
}
new Set(['Mike', 'Tom', undefined]).forEach(logSetElements);
Output:
s[Mike] = Mike
s[Tom] = Tom
s[undefined] = undefined
The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.
const names = new Set();
names.add('Tom');
names.add('Mike');
const setIterator = names.values();
console.log(setIterator);
Output:
SetIterator {"Tom", "Mike"}
- The entries() method returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order.
- For Set objects there is no key like in Map objects. However, to keep the API similar to the Map object, each entry has the same value for its key and value here, so that an array [value, value] is returned.
const names = new Set();
names.add('Tom');
names.add('Mike');
const setIterator = names.entries();
for (const entry of setIterator) {
console.log(entry);
}
Output:
["Tom", "Tom"]
["Mike", "Mike"]