JavaScript Sets

JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
This tutorial will teach you JavaScript from basic to advanced.
Post Reply
Guest

JavaScript Sets

Post by Guest »

JavaScript Sets


A JavaScript Set is a collection of unique values.
Each value can only occur once in a Set.

Essential Set Methods

MethodDescription
new Set()Creates a new Set
add()Adds a new element to the Set
delete()Removes an element from a Set
has()Returns true if a value exists in the Set
forEach()Invokes a callback for each element in the Set
values()Returns an iterator with all the values in a Set
PropertyDescription
sizeReturns the number of elements in a Set


How to Create a Set
You can create a JavaScript Set by:

Passing an Array to new Set()
Create a new Set and use add() to add values
Create a new Set and use add() to add variables


The new Set() Method
Pass an Array to the new Set() constructor:

Example

// Create a Set
const letters = new Set(["a","b","c"]);

Try it Yourself »

Create a Set and add values:

Example

// Create a Set
const letters = new Set();

// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");

Try it Yourself »

Create a Set and add variables:

Example

// Create a Set
const letters = new Set();

// Create Variables
const a = "a";
const b = "b";
const c = "c";

// Add Variables to the Set
letters.add(a);
letters.add(b);
letters.add(c);

Try it Yourself »


The add() Method

Example

letters.add("d");
letters.add("e");

Try it Yourself »

If you add equal elements, only the first will be saved:

Example

letters.add("a");
letters.add("b");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");

Try it Yourself »








The forEach() Method
The forEach() method invokes (calls) a function for each Set element:

Example

// Create a Set
const letters = new Set(["a","b","c"]);

// List all Elements
let text = "";
letters.forEach (function(value) {
  text += value;
})

Try it Yourself »


The values() Method
The values() method returns a new iterator object containing all the values in a Set:

Example

letters.values()   // Returns [object Set Iterator]

Try it Yourself »

Now you can use the Iterator object to access the elements:

Example

// List all Elements
let text = "";
for (const x of letters.values()) {
  text += x;
}

Try it Yourself »














+1

Reference: https://www.w3schools.com/js/js_sets.asp
Post Reply