Javascript Es6 Set tutorials | Typescript Set Examples

Set is a Data structure that is used to store unique elements introduced in ES6. In this blog post, We are going to cover the Set tutorials in typescript/javascript with examples.

Other Classes are Map , WeakSet and WeakMap

ES6 Set Data structure

Es6 introduced the Set class for storing unique elements. javascript supports Set, Map, WeakMap data structures with Es6 version.

Set preserves the order in which values are inserted. Doing Iteration also shows the same order. Typescript has no built-in classes supported for Set, But Typescript supports the same data structure that ES6 supports with the setting below configuration

Es6 classes use in typescript with some configuration In the tsconfig.json file, add “lib”: [“es6”] or you can add polyfill.js for this classes. An example mentioned will work in Typescript and Javascript.

Set Syntax

The set object declares using let and a new keyword.

new Set([iterable]);

Parameters - Iterable data is passed, such as an array. All the elements are added to the new Set and return the Set Object. if the parameter is empty or Null, an Empty Set is created.

Set Object Creation Examples

We will see how we can add/remove/get/contain an element of a Set object. Empty Object Creation object set creation is simple.

new Set(); //outputs {}

adding array elements to Set:

let setData = new Set(["one", "two", "three"]); // {"one", "two", "three"}

We can also add elements using the add() method.

new Set().add('one').add('two).add('three');  // {"one", "two", "three"}

The above example used chaining of the add method to the Set object. add() method adds the elements and returns an object reference, not the added element.

Set add() method examples

this method adds the element to the end of a set object and returns the set object.

syntax:

Set<any>.add(value:any):Set<any>

parameter - add specific value to set. Return - return Set object.

Example:

var myset = new Set();
myset.add(1);
myset.add(13).add(14).add(51);
console.log(myset); // outputs 1, 13, 14, 51

Set delete() method examples

It deletes an element from Set Object. Syntax:

Set<any>.delete(value:any):boolean

Parameters - value is to be deleted from the Set. Returns - true, if a value exists in the set and is deleted from Set, false - if unable to delete and value not exist in Set.

Example:

var myset = new Set();
myset.add(1);
myset.add(13).add(14).add(51);
console.log(myset.delete(1)); // Outputs true
console.log(myset.delete(43)); // Outputs false

Set clear() method examples

This method removes all elements from a Set Syntax:

Set<any>.clear():void

It does not take any parameters and returns nothing Examples:

var myset = new Set([11, 12, 13, 14, 15]);
console.log(myset); //outputs {11, 12, 13,14, 15}
myset.clear();
console.log(myset); // outputs empty set {}

Set has() method examples

This method returns true if a value exists in the Set. Syntax:

Set<any>.has(value:any):boolean

Parameter - value to check-in set returns - true if a value exists in a set, else false Example:

var myset = new Set([11, 12, 13, 14, 15]);
console.log(myset.has(11)); // output true
console.log(myset.has(131)); // output false

Set entries() method examples

This method is used to iterate the elements in the Set object. This returns a new Iterator object that has an array of the element. Each element contains [value,value] Syntax:

Set<any>.entries():IterableIterator<any,any>

No parameters passed Returns Iterator with key and values. Here key and value are of the same element in a set. Example:

var myset = new Set([11, 12, 13, 14, 15]);
var entriesIterator = myset.entries();
console.log(entriesIterator.next().value); // outputs 11
console.log(entriesIterator.next().value); // outputs 12
console.log(entriesIterator.next().value); // outputs 13

Set keys() method examples

This method is used to iterate the elements in the Set object. This returns all the elements from Set in insertion order Syntax:

Set<any>.keys():IterableIterator<any>

Return elements iterator. Example:

var myset = new Set([11, 12, 13, 14, 15]);
var keysIterator = myset.keys();
console.log(keysIterator.next().value); // outputs 11
console.log(keysIterator.next().value); // outputs 12
console.log(keysIterator.next().value); // outputs 13

Set values() method examples

This method is used to iterate the elements in the Set object of the same insertion order. This is the same as the keys() method Syntax:

Set<any>.values():IterableIterator<any>

Return elements/values iterator. Example:

var myset = new Set([11, 12, 13, 14, 15]);
var valuesIterator = myset.values();
console.log(valuesIterator.next().value); // outputs 11
console.log(valuesIterator.next().value); // outputs 12
console.log(valuesIterator.next().value); // outputs 13

Set forEach() method examples

This is used to iteration for a set of elements. This takes a callback function which applies to each element of a Set Syntax:

Set<any>.forEach(callbackFn[,parameters]):void

callbackFn - It is a function that executes for each element of Set parameters - values passed callbackFn accepts three arguments the First argument is key, the second argument values, and the third argument is the Set object. Example:

var myset = new Set([11, 12, 13, 14, 15]);
// one way to use forEach
myset.forEach(display);
function display(key) {
  console.log(key);
}
// Another way to use forEach
myset.forEach(function (value) {
  console.log(value);
});

set size example

Returns the size of the unique elements in a set Syntax:

Set<any>.size():number

Returns - Number of elements in a set Example:

var myset = new Set([11, 12]);
console.log(myset.size); // outputs 2

for…Of Set Example

This is another way of doing iteration in a Set of Objects.

var myset = new Set([11, 12, 13, 14, 15]);
for (let noValue of myset) {
  console.log(noValue); //outputs 11,12,13,14,15
}

Duplicate/unique Element Example

In this, Duplicates elements are added, but the Set accepts unique elements

var myset = new Set([11, 12, 11]);
console.log(myset);
var myset = new Set([{ name: "one" }, { name: "one" }, { name: "one" }]);
console.log(myset); //outputs  {{name: 'one'}, {name: 'one'}, {name: 'one'}}

Unique value are tested using === operator. For primitive values, This is simple and easy to understand For Object uniqueness - === returns if both object references are equal. In the second example, added three objects, three different references, Three objects are added How to Convert Set to Array Set accepts an iterable object as parameters for adding elements. An array that implements Iterable can be passed as a parameter

var array = [3, 14, 35];
var myset = new Set(array);
console.log(myset.size === array.length); // true
console.log(myset.has(14)); // true

filter, map, and reduce Example

map and reduce and filter operators will not support a Set object using javascript and typescript. But we can apply some mechanisms in javascript and typescript. First, you need to convert to an array using the Es6 Spread operator, then we can apply these methods.

const mySet = new Set([0,1,4,8]);
[...mySet].map()
 [...mySet].filter()
[...mySet].reduce()

How to do a merge of multiple sets?

Using the forEach method, We can merge multiple sets

var first = new Set([11, 12, 13]);
var second = new Set([41, 51, 61]);
second.forEach(first.add, first);
console.log(first); // 11,12,13,41,51,61