js - sets

// Set : stores unique values

// initialising an empty set
const mySet = new Set();

// adding vlaues in set

mySet.add('this')
mySet.add({key : "value"})
mySet.add(35)
mySet.add(true)
mySet.add('this')//cant take repeated values
mySet.add("gone case") 
// console.log(mySet);


// Using constructor to initialize the set
// const mySet2 = new Set([1,24,'this',false,{a:4 , b:'hello'},'this'])
// console.log(mySet2);

// getting size of set

// console.log(mySet.size);

// checking value exist in set or not
// console.log(mySet.has(35));

// removing value from set

// console.log("before removal",mySet);

// console.log(mySet.delete('gone case'));
// console.log("after removal", mySet);

// iterate the set

// for(let item of mySet){
// console.log(item);
// }

// using forEach loop
// mySet.forEach(element => {
//     console.log(element);
    
// });

// convertin set to array
// let mySetArray = Array.from(mySet);
// console.log("ARRaY of set", typeof(mySetArray));
// console.log("ARRaY of set", mySetArray);





/* example : removing duplicates from Array

array with duplicates
let newArray = [34,23,'this','hello', {a : 5,b: 6},'this']
console.log("Array with duplicate ", newArray);

/converting array to set
var myArraySet = new Set(newArray);

 converting set back to array with duplcates removed
let newArray2 = Array.from(myArraySet);
console.log("Array with duplicates removed ", newArray2);

*/

0 Comments