let mySet =newSet()
mySet.add(1)// Set [ 1 ]
mySet.add(5)// Set [ 1, 5 ]
mySet.add(5)// Set [ 1, 5 ]
mySet.add('some text')// Set [ 1, 5, 'some text' ]let o ={a:1,b:2}
mySet.add(o)
mySet.add({a:1,b:2})// o is referencing a different object, so this is okay
mySet.has(1)// true
mySet.has(3)// false, since 3 has not been added to the set
mySet.has(5)// true
mySet.has(Math.sqrt(25))// true
mySet.has('Some Text'.toLowerCase())// true
mySet.has(o)// true
mySet.size// 5
mySet.delete(5)// removes 5 from the set
mySet.has(5)// false, 5 has been removed
mySet.size// 4, since we just removed one valueconsole.log(mySet)// logs Set(4) [ 1, "some text", {…}, {…} ] in Firefox// logs Set(4) { 1, "some text", {…}, {…} } in Chrome
// Use to remove duplicate elements from the array const numbers =[2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]//spreading numbers of the object into an array using the new operatorconsole.log([...newSet(numbers)])// [2, 3, 4, 5, 6, 7, 32]
Aset is a collection of items which are unique i.e no element can be repeated.SetinES6 are ordered: elements of the set can be iterated in the insertion
order.Set can store any types of values whether primitive or objects.var set4 =newSet();
// Use to remove duplicate elements from the array const array =[2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]//spreading numbers of the object into an array using the new operatorconsole.log([...newSet(array)])// [2, 3, 4, 5, 6, 7, 32]
const mySet1 =newSet()
mySet1.add(1)// Set [ 1 ]
mySet1.add(5)// Set [ 1, 5 ]
mySet1.add(5)// Set [ 1, 5 ]
mySet1.add('some text')// Set [ 1, 5, 'some text' ]const o ={a:1,b:2}
mySet1.add(o)
mySet1.add({a:1,b:2})// o is referencing a different object, so this is okay
mySet1.has(1)// true
mySet1.has(3)// false, since 3 has not been added to the set
mySet1.has(5)// true
mySet1.has(Math.sqrt(25))// true
mySet1.has('Some Text'.toLowerCase())// true
mySet1.has(o)// true
mySet1.size// 5
mySet1.delete(5)// removes 5 from the set
mySet1.has(5)// false, 5 has been removed
mySet1.size// 4, since we just removed one value
mySet1.add(5)// Set [1, 'some text', {...}, {...}, 5] - a previously deleted item will be added as a new item, it will not retain its original position before deletionconsole.log(mySet1)// logs Set(5) [ 1, "some text", {…}, {…}, 5 ] in Firefox// logs Set(5) { 1, "some text", {…}, {…}, 5 } in Chrome
// create Setconst set1 =newSet();// an empty setconsole.log(set1);// Set {}// Set with multiple types of valueconst set2 =newSet([1,'hello',{count:true}]);console.log(set2);// Set {1, "hello", {count: true}}
const id =newSet();
id.add(1);
id.add(2);
id.add(3);
id.add(3);// duplicate value will not be addedconsole.log(id);// output: Set {1, 2, 3}
id.delete(2);// delete the value 2 from the setconsole.log(id);// output: Set {1, 3}
id.has(2);// check if the set has the value 2 // output: trueconsole.log(id);//order is not guaranteed