Understanding Set in JavaScript
Set is a built-in object in JavaScript introduced in ES6. It allows you to store unique values of any type—whether primitive values or object references. This makes it a handy tool for managing collections of data where duplicate values are not allowed.
Creating a Set
To create a Set, you can use the Set constructor:
const mySet = new Set();
You can also initialize a Set with an array or iterable:
const mySet = new Set([1, 2, 3, 4]);
console.log(mySet); // Set(4) { 1, 2, 3, 4 }
Basic Operations on a Set
1. Adding Elements
You can add elements to a Set using the .add() method:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // Duplicate, will not be added
console.log(mySet); // Set(2) { 1, 2 }
2. Deleting Elements
Remove an element using the .delete() method:
mySet.delete(2);
console.log(mySet); // Set(1) { 1 }
3. Checking Existence
Use .has() to check if a value exists in the Set:
console.log(mySet.has(1)); // true console.log(mySet.has(3)); // false
4. Getting the Size
Retrieve the number of elements using .size:
console.log(mySet.size); // 1
5. Clearing the Set
Remove all elements using .clear():
mySet.clear();
console.log(mySet); // Set(0) {}
Iterating Through a Set
You can iterate through a Set using various methods:
Using for...of Loop
const mySet = new Set([1, 2, 3]);
for (const value of mySet) {
console.log(value);
}
Using forEach() Method
mySet.forEach(value => console.log(value));
Common Use Cases for Set
1. Removing Duplicates from an Array
const array = [1, 2, 3, 4, 1, 2]; const uniqueArray = [...new Set(array)]; console.log(uniqueArray); // [1, 2, 3, 4]
2. Finding Intersection of Two Arrays
const arr1 = [1, 2, 3, 4]; const arr2 = [3, 4, 5, 6]; const set1 = new Set(arr1); const intersection = arr2.filter(value => set1.has(value)); console.log(intersection); // [3, 4]
3. Finding Union of Two Arrays
const arr1 = [1, 2, 3, 4]; const arr2 = [3, 4, 5, 6]; const union = [...new Set([...arr1, ...arr2])]; console.log(union); // [1, 2, 3, 4, 5, 6]
4. Finding Difference of Two Arrays
const arr1 = [1, 2, 3, 4]; const arr2 = [3, 4, 5, 6]; const set1 = new Set(arr1); const difference = arr1.filter(value => !set1.has(value)); console.log(difference); // [1, 2]
5. Finding Pairs with a Given Sum
Given an array, find all pairs whose sum equals a target value:
function findPairs(arr, target) {
const set = new Set();
const pairs = [];
for (const num of arr) {
const complement = target - num;
if (set.has(complement)) {
pairs.push([num, complement]);
}
set.add(num);
}
return pairs;
}
console.log(findPairs([1, 2, 3, 4, 5], 6)); // [[3, 3], [4, 2], [5, 1]]
Advanced Questions on Set
1. How to Convert a Set Back to an Array?
Use the spread operator or Array.from():
const mySet = new Set([1, 2, 3]); const array = [...mySet]; console.log(array); // [1, 2, 3]
2. Can a Set Contain Objects?
Yes, a Set can hold objects:
const obj1 = { id: 1 };
const obj2 = { id: 2 };
const mySet = new Set([obj1, obj2]);
console.log(mySet.has(obj1)); // true
Limitations of Set
- No direct access to elements by index.
- Cannot hold duplicate values.
- Not optimized for scenarios requiring frequent element lookup by index.
Set in JavaScript is a powerful and versatile tool, particularly for managing collections of unique values. From deduplication to solving complex problems like array intersections and unions, Set can significantly simplify your code while improving performance.
In JavaScript, Map and Object are both used to store key-value pairs, but they have some key differences in functionality and usage:
1. Key Types
- Map:
- Keys can be of any data type (e.g., objects, functions, primitives).
- Example:
const map = new Map();
map.set(1, 'number key'); // Number
map.set('1', 'string key'); // String
map.set({}, 'object key'); // Object
- Object:
- Keys must be strings or symbols (non-string keys are converted to strings).
- Example:
const obj = {};
obj[1] = 'number key'; // Key becomes "1"
obj['1'] = 'string key'; // Same as above
obj[{}] = 'object key'; // Key becomes "[object Object]"
2. Order of Keys
- Map:
- Maintains the order of keys as they are added.
- Object:
- Does not guarantee key order for non-integer keys. Integer keys are sorted in ascending order.
3. Size
- Map:
- Has a
sizeproperty to get the number of key-value pairs.
const map = new Map();
map.set('a', 1);
console.log(map.size); // 1
- Object:
- Does not have a direct property for size. You can calculate it using
Object.keys().
const obj = { a: 1 };
console.log(Object.keys(obj).length); // 1
4. Performance
- Map:
- Optimized for frequent additions and removals of key-value pairs.
- Object:
- Slower for frequent additions and removals because it's designed as a general-purpose structure.
5. Default Keys
- Map:
- Does not have any default keys.
- Object:
- Has default keys inherited from
Object.prototype(e.g.,toString,valueOf). These can cause conflicts unless overridden.
const obj = {};
console.log(obj.toString); // Default inherited method
6. Iteration
- Map:
- Directly iterable using
for...ofor.forEach().
const map = new Map();
map.set('a', 1);
map.set('b', 2);
for (const [key, value] of map) {
console.log(key, value);
}
- Object:
- Requires
Object.keys(),Object.values(), orObject.entries()to iterate.
const obj = { a: 1, b: 2 };
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}
7. Use Cases
- Map:
- When you need a collection with guaranteed order, varied key types, and frequent modifications.
- Object:
- When you need a simple structure with string/symbol keys or for creating plain data structures.
Summary Table
Feature Map Object Key Types Any data type Strings or Symbols Key Order Maintains insertion order Integer keys sorted; others unordered Size Property .size Object.keys(obj).length Iteration Directly iterable Requires helper methods Performance Better for frequent ops General-purpose usage Default Keys None Inherited from Object Conclusion:
- Use Map when working with dynamic collections, varied key types, or guaranteed key order.
- Use Object for static or structured data.
