1// Use to remove duplicate elements from the array
2
3const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
4
5//spreading numbers of the object into an array using the new operator
6console.log([...new Set(numbers)])
7
8// [2, 3, 4, 5, 6, 7, 32]
1let mySet = new Set()
2
3mySet.add(1) // Set [ 1 ]
4mySet.add(5) // Set [ 1, 5 ]
5mySet.add(5) // Set [ 1, 5 ]
6mySet.add('some text') // Set [ 1, 5, 'some text' ]
7let o = {a: 1, b: 2}
8mySet.add(o)
9
10mySet.add({a: 1, b: 2}) // o is referencing a different object, so this is okay
11
12mySet.has(1) // true
13mySet.has(3) // false, since 3 has not been added to the set
14mySet.has(5) // true
15mySet.has(Math.sqrt(25)) // true
16mySet.has('Some Text'.toLowerCase()) // true
17mySet.has(o) // true
18
19mySet.size // 5
20
21mySet.delete(5) // removes 5 from the set
22mySet.has(5) // false, 5 has been removed
23
24mySet.size // 4, since we just removed one value
25
26console.log(mySet)
27// logs Set(4) [ 1, "some text", {…}, {…} ] in Firefox
28// logs Set(4) { 1, "some text", {…}, {…} } in Chrome
29
1// set is used for storing unique values
2const firstSet = new Set([1, 2, 3]);
3
4firstSet.add('hi'); //adding value to set
5
6firstSet.add(3); //this will not give any error and it will also not be added
7
8firstSet.delete('hi');//removing value from set
9
10console.log(firstSet.has('hi'));//checking 'hi' is in the set or not
11
12// showing all values in the set
13console.log(firstSet);
14for (const entry of firstSet.values()) {
15 console.log(entry);
1A set is a collection of items which are unique i.e no element can be repeated.
2Set in ES6 are ordered: elements of the set can be iterated in the insertion
3order. Set can store any types of values whether primitive or objects.
4var set4 = new Set();
1const language = {
2 set current(name) {
3 this.log.push(name);
4 },
5 log: []
6};
7
8language.current = 'EN';
9language.current = 'FA';
10
11console.log(language.log);
12// expected output: Array ["EN", "FA"]
1
2
3
4
5 let chars = new Set(['a', 'a', 'b', 'c', 'c']);Code language: JavaScript (javascript)