Sets using JavaScript.

MOHD YUSUFMOHD YUSUF
1 min read

Set is a well-defined collection of elements. It stores unique elements. If you insert duplicate element in a set than it will discard that duplicate element. Let's understand this with another scenario. If you accidently entered an element two or more time than it will store only once others accidentally entered elements will be discarded.

Here is the syntax for set in JavaScript.

const setA = new Set();
const setB = new Set([1,2,3,4,5]);
const arr = [1,2,3,4,5,6];
const setC = new Set(arr);

// or same this write as ↴ 

constD = new Set([...arr]);

Let's understand with an example:

const array = [1,2,3,4,5,4,3,2,1];
console.log(array); // It will print ↴
                    // [ 1,2,3,4,5,4,3,2,1 ]

const setE = new Set(array);
console.log(setE);   // It will print ↴
                     // set(5) {1,2,3,4,5}
// set store unique values.

Intersection:

Intersection is an operator that is used to elaborates common elements in two sets.

Code for Intersection:

setA ◠ setB

let setA = new Set([1,2,3,4,5,6,7,8,9]);
let setB = new Set([2,4,5,6,8]);

console.log([...setA].filter(ele => setB.has(ele)));

Difference:

Difference is also an operator that is used to elaborates the elements of a set that are not present in another set.

Code for difference:

setC - setD

let setC = new Set([1,2,3,4,5,6,7,8,9]);
let setD = new Set([2,4,5,6,8]);

console.log([...setC].filter(ele => setD.has(ele)));
0
Subscribe to my newsletter

Read articles from MOHD YUSUF directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MOHD YUSUF
MOHD YUSUF