Javascript - Set

About

The Set interface represents a set data type and works only with primitive type as there is no way to define an object equality function.

Object as set

This article is about the Set interface in javascript but you can also create a set with an object where the property are unique.

In this case, if you want to declare the type of the object in Jsdoc, you would use 1):

/**
 * A map-like object that maps arbitrary `string` properties to `number`s.
 *
 * @type {Object.<string, number>}
 */
var stringToNumber;
 
/** @type {Object.<number, object>} */
var arrayLike;

Example

  • Declaration
let colorSet = new Set();
  • Add/Delete
colorSet.add("blue");
colorSet.add("blue");
colorSet.add("red");
colorSet.add("orange");
colorSet.delete("blue");
  • Size
console.log("Set size should be 2: "+colorSet.size);
  • Contains (has)
console.log("Has color red ? "+colorSet.has("red"));
console.log("Color iteration:");
for (let color of colorSet) console.log("    * "+color);
  • Keys iteration
console.log("Colors Key:");
for (let colorKey of colorSet.keys()) console.log("    * "+colorKey);
  • Values iteration
console.log("Colors Values:");
for (let colorValue of colorSet.values()) console.log("    * "+colorValue);

Interface

Interface definition in declaration file

interface Set<T> {
    add(value: T): this;
    clear(): void;
    delete(value: T): boolean;
    forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
    has(value: T): boolean;
    readonly size: number;
}

Management

Declaration

let colorSet = new Set();
let numberSet = new Set([1, 2, 3, 4])

to Array

to an array with the spread operator

let numberArray = [...numberSet];
  • Array.from
let myArr = Array.from(mySet)

Add

colorSet.add("blue");

Delete

  • Delete
colorSet.delete("blue");

Contains (has)

console.log("Has color red ? "+colorSet.has("red"));

Iteration

for of

In a set, the key is also the value With for of:

  • Key Color iteration
console.log("Color iteration:");
for (let color of colorSet) console.log("    * "+color);
  • Keys iteration explicit
console.log("Colors Key:");
for (let colorKey of colorSet.keys()) console.log("    * "+colorKey);
  • Values iteration
console.log("Colors Values:");
for (let colorValue of colorSet.values()) console.log("    * "+colorValue);

foreach

let mySet = new Set([1,2,3,4,1]);
mySet.forEach(function(value) {
  console.log(value)
})

Functional Programming

To use functional programming, you need to transform the set in an array.

Example:

let mySet = new Set([1,2,3,4,1]);
[...mySet].filter(e => e!=2).map(e => console.log(e));

Intersect

Set - Intersect

set1 = new Set([1, 2, 3, 4])
set2 = new Set([2, 4])
let intersection = new Set([...set1].filter(x => set2.has(x)))
for (let element of intersection ) console.log(element );

Diff

Set - Difference

  • Asymmetric difference (where the first set is the driver)
function difference(setA, setB) {
    return new Set([...setA].filter(x => !setB.has(x)))
    // Longer version
    // let _difference = new Set(setA)
    // for (let elem of setB) {
    //     _difference.delete(elem)
    // }
    // return _difference
}
  • symmetric difference implementation (where the difference on the two set is shown)
function symmetricDifference(setA, setB) {
    let _difference = new Set(setA)
    for (let elem of setB) {
        if (_difference.has(elem)) {
            _difference.delete(elem)
        } else {
            _difference.add(elem)
        }
    }
    return _difference
}
  • The set
let setA = new Set([1, 2, 3, 4])
let setB = new Set([3, 4, 5, 6])

let diff = difference(setA,setB);
console.log("The difference is");
for (let e of diff ) console.log(" * "+e);

let symDiff = symmetricDifference(setA,setB);
console.log("The asymmetric difference is");
for (let e of symDiff ) console.log(" * "+e);

Equality

Logical Data Modeling - Equivalence Relationship (Equality)

  • Implementation of an asymmetric equality.
function areEquals(setA, setB){
  if (setA.size != setB.size) {
    return false;
  } else {
    let difference = new Set([...setA].filter(x => !setB.has(x)))
    return difference.size == 0;
  }
}
  • Order does not matter
set1 = new Set([1, 2])
set2 = new Set([2, 1])
console.log("Order does not matter: "+areEquals(set1,set2));
  • False
set1 = new Set([1])
set2 = new Set([1,2])
console.log("Equality is symmetric. Diff is : "+areEquals(set1,set2));
  • Output

Documentation / Reference





Discover More
Javascript - Array

array in Javascript can contain any type of data. Different types of values can be stored within the same array Because arrays are special objects (as typeof implies), they can also have properties, including...
Javascript Object - JSON.Stringify

JSON.stringify transform an object as a string with a JSON structure A JSON string from a javascript object How to transform a set to an array By returning undefined from the replacer, you...



Share this page:
Follow us:
Task Runner