JavaScript Sets provide several methods for manipulating and working with the data they contain. Here's an overview of some common Set methods:
Adds a new element to the Set. If the value already exists, it is ignored.
const mySet = new Set();
mySet.add('apple');
mySet.add('banana');
mySet.add('apple'); // Ignored, as 'apple' already exists in the Set
Removes a specified value from the Set. Returns true if the value was removed successfully, otherwise false.
const mySet = new Set(['apple', 'banana', 'orange']);
mySet.delete('banana');
console.log(mySet); // Output: Set { 'apple', 'orange' }
Removes all elements from the Set.
const mySet = new Set(['apple', 'banana', 'orange']);
mySet.clear();
console.log(mySet); // Output: Set {}
Returns true if the Set contains the specified value, otherwise false.
const mySet = new Set(['apple', 'banana', 'orange']);
console.log(mySet.has('banana')); // Output: true
console.log(mySet.has('grape')); // Output: false
Returns the number of elements in the Set.
const mySet = new Set(['apple', 'banana', 'orange']);
console.log(mySet.size); // Output: 3
Executes a provided function once for each value in the Set, in insertion order.
const mySet = new Set(['apple', 'banana', 'orange']);
mySet.forEach((value, valueAgain, set) => {
console.log(value);
});
Returns a new iterator object that contains the values for each element in the Set, in insertion order.
const mySet = new Set(['apple', 'banana', 'orange']);
const iterator = mySet.values();
console.log(iterator.next().value); // Output: 'apple'
console.log(iterator.next().value); // Output: 'banana'
console.log(iterator.next().value); // Output: 'orange'
Returns a new iterator object that contains an array of `[value, value]` pairs for each element in the Set, in insertion order.
const mySet = new Set(['apple', 'banana', 'orange']);
const iterator = mySet.entries();
console.log(iterator.next().value); // Output: ['apple', 'apple']
console.log(iterator.next().value); // Output: ['banana', 'banana']
console.log(iterator.next().value); // Output: ['orange', 'orange']
These are some of the commonly used methods available for working with JavaScript Sets. They provide flexibility and convenience when manipulating sets of unique values.