AnyCompiler

Sets

Set ek collection hai jiska sirf ek usool hai: usme har value unique hoti hai. Duplicate add karo to kuch nahi hota — woh pehle se hi wahan mojood hai.

let numbers = new Set([1, 2, 3, 2, 1]);
console.log(numbers);

numbers.add(4);
console.log(numbers);

console.log(numbers.has(2));
console.log(numbers.size);
Output
Set { 1, 2, 3 }
Set { 1, 2, 3, 4 }
true
4

new Set([1, 2, 3, 2, 1]) bante hi sirf teen unique values mein simat jaata hai. has() membership check karta hai, aur size (length nahi) count deta hai.

Set aur array ke darmiyan convert karna

Sets mein map() ya filter() jaise array methods directly nahi hote — jab woh chahiye ho to spread syntax [...set] istemal kar ke convert karo.

let unique = [...new Set([1, 1, 2, 2, 3])];
console.log(unique);
Output
[ 1, 2, 3 ]

Yeh waqai kaam ki cheez hai, sirf ek tamasha nahi: array ko deduplicate karna bilkul yahi pattern hai — duplicates hatane ke liye ise Set mein wrap karo, phir wapas ek plain array mein spread kar do.

Aage: conditional statements — apne code ko asal mein ek value ki bunyad par branch karwana.

Practice Exercise

numbers = new Set([1, 2, 2, 3, 3, 3]) banao. numbers.size print karo, phir numbers.has(2) istemal kar ke print karo ke numbers mein value 2 hai ya nahi.