JavaScript Set Reference

JavaScript Set Reference

  • JavaScript provides various methods and properties for working with set objects, which are referred to as the set reference.
  • A set is a collection of unique values that doesn’t allow duplicates.
  • A set can hold any value, whether primitive or object references.

Creating a set

  • To create a set in JavaScript use the Set object, which allows you to store unique values of any type(e.g., primitive values, objects).
  • A new set can either be empty or initialized with a specific value.

Example:

let emptyset = new set();// Empty set
let withvalueset = new set([1,2,3,'apple',true]);//Set with initial values

In this example, we have created two sets first one is empty, and the second has pre-inserted values.

Adding Elements into an empty set

Use the .add() method to insert elements into a set, which automatically ignores duplicate values.

emptySet.add(1);
emptyset.add(5);
emptyset.add(5);//duplicate
emptyset.add('Hello Coders.');

In the above example, we added values into the set emptyset in which the third value is a duplicate of the second value and it will be ignored.

Properties:

1. size

Returns the number of elements in a set.

console.log(emptyset.size);

It will return the size of the emptyset.

Method:

1. add(value)

Adds a new element to the set.

emptyset.add(10);

This will add 10 to the emptyset.

2. delete(value)

Removes a specific element from the set.

emptyset.delete(1);

This will remove the element having 1 as its value.

3. has(value)

Returns true if the set contains the specified value otherwise returns false.

console.log(emptyset.has(10));

Output: 

true

4. clear()

Removes all elements from the set.

emptyset.clear();

Converting Set to Array:

To convert a set into an array, take a new variable (e.g., array) and use Array.from() to complete the task.
let array = Array.from(withvalueset);

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top