Saturday, March 30, 2024

What are Sets in Javascript?

A JavaScript Set is a collection of unique values of any data type.

How to Create a Set?

You can create a JavaScript Set by:

1) Passing an Array to new Set()

Ex: const fruits = new Set(["apple","orange","mango"]);

2) Create a new Set and use add() to add values

Ex: const fruits = new Set();

fruits.add("apple");

fruits.add("orange");

fruits.add("mango");

3) Create a new Set and use add() to add variables

Ex: const fruits = new Set();

const a = "apple";

const b = "orange";

const c = "mango";

fruits.add(a);

fruits.add(b);

fruits.add(c);

What are avaialble Set methods?

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

clear(): Removes all elements from a Set

forEach(): Invokes a callback for each element

const fruits = new Set(["apple","orange","mango"]);

fruits.forEach (function(value) {

  let text = "";

  text += value;

  console.log(text);

})

Output:

apple

orange

mango

values(): Returns an Iterator with all the values in a Set

const fruits = new Set(["apple","orange","mango"]);

for (const x of fruits.values()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

apple

orange

mango

keys(): Same as values()

const fruits = new Set(["apple","orange","mango"]);

for (const x of fruits.keys()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

apple

orange

mango

entries(): Returns an Iterator with the [value,value] pairs from a Set

const fruits = new Set(["apple","orange","mango"]);

for (const x of fruits.entries()) {

  let text1 = "";

  text1 += x  ;

  console.log(text1);

}

Output:

apple,apple

orange,orange

mango,mango

size: Returns the number elements in a Set

const fruits = new Set(["apple","orange","mango"]);

console.log(fruits.size);

Output:

3

No comments:

Post a Comment