JavaScript : Set Methods

JavaScript Sets provide several methods for manipulating and working with the data they contain. Here's an overview of some common Set methods:

1. add(value)


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

 

2. delete(value)


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' }

 

3. clear()


Removes all elements from the Set.


const mySet = new Set(['apple', 'banana', 'orange']);

mySet.clear();
console.log(mySet); // Output: Set {}

 

4. has(value)


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

 

5. size


Returns the number of elements in the Set.


const mySet = new Set(['apple', 'banana', 'orange']);

console.log(mySet.size); // Output: 3
 

6. forEach(callbackFn)


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);
});

 

7. values()


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'

 

8. entries()


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.