المجموعات (Set) في JavaScript (Node.js): دليل شامل
Sets in JavaScript
What is a Set and why do you need it?
Imagine you have a box where you cannot put two identical toys. If you try to put a second identical ball in there, the box simply won't let you — the ball will remain as a single copy. In programming, such a "box" is called a Set.
A Set is a collection that stores only unique values. If you add the same number or word twice, only one copy remains in the set. This is very convenient when you need to remove duplicates or check if something exists in a list.
Basic Syntax
To create a new set, use the Set() constructor:
// Creating an empty set
let mySet = new Set();
You can create a set with elements immediately by passing an array to the constructor:
let fruits = new Set(['apple', 'banana', 'apple', 'orange']);
console.log(fruits);
// Output: Set(3) { 'apple', 'banana', 'orange' }
// Notice: 'apple' appears only once!
Basic methods for working with a set:
add(value)— adds a value to the setdelete(value)— removes a value from the sethas(value)— checks if a value exists in the set (returnstrueorfalse)size— property showing the number of elements in the setclear()— removes all elements from the set
Here's how it works in a program:
// Example: working with a set
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let guests = new Set();
guests.add('Anna');
guests.add('Peter');
guests.add('Anna'); // Anna is already there, so nothing changes
guests.add('Maria');
console.log('Number of guests:', guests.size); // 3
console.log('Is Peter there?', guests.has('Peter')); // true
guests.delete('Peter');
console.log('Is Peter there after deletion?', guests.has('Peter')); // false
rl.close();
How to iterate over Set elements
A set can be iterated using a for...of loop:
let colors = new Set(['red', 'blue', 'green']);
for (let color of colors) {
console.log(color);
}
// Output:
// red
// blue
// green
You can also convert a set back to an array using Array.from() or the spread operator [...set]:
let numbers = new Set([1, 2, 3, 2, 1]);
let arr = [...numbers];
console.log(arr); // [1, 2, 3]
Analysis of Typical Problems
Let's analyze how to solve problems similar to what you'll be doing.
Problem 1: Unique Pizza Ingredients
The user enters ingredients separated by commas. You need to show only the unique ones.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter ingredients separated by commas: ', (input) => {
// Split the string by commas and remove extra spaces
let ingredients = input.split(',').map(item => item.trim());
// Create a set to remove duplicates
let uniqueIngredients = new Set(ingredients);
console.log('Unique ingredients:');
for (let ingredient of uniqueIngredients) {
console.log('- ' + ingredient);
}
rl.close();
});
Problem 2: Merging Shopping Lists
You have your own list and a friend's list. You need to merge them without duplicates.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let myList = ['milk', 'bread', 'cheese', 'apples'];
let friendList = ['cheese', 'juice', 'cookies', 'milk'];
// Create a set from your list
let finalList = new Set(myList);
// Add elements from the friend's list
for (let item of friendList) {
finalList.add(item);
}
console.log('Final shopping list:');
for (let item of finalList) {
console.log('- ' + item);
}
// Output: milk, bread, cheese, apples, juice, cookies
rl.close();
Problem 3: Removing Items from a List
You have a list of products. You decided to remove some of them. You need to delete them from the set.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let shoppingList = new Set(['milk', 'bread', 'cheese', 'apples', 'juice']);
rl.question('Which products to remove? (separated by commas): ', (input) => {
let toRemove = input.split(',').map(item => item.trim());
for (let item of toRemove) {
shoppingList.delete(item);
}
console.log('Remaining in the list:');
for (let item of shoppingList) {
console.log('- ' + item);
}
rl.close();
});
Common Beginner Mistakes
- Confusing Set with Array. An array can contain duplicate elements, but a Set cannot. If you need to preserve order and allow duplicates — use an array. If you need uniqueness — use a Set.
- Trying to access an element by index. Sets don't have indices! You cannot write
mySet[0]— it won't work. To get an element, use a loop or convert the Set to an array. - Forgetting that Set automatically removes duplicates. If you add the same value multiple times, only one copy remains in the set. Sometimes this is unexpected, but most often — it's exactly what you need.
- Confusing
sizeandlength. An array has thelengthproperty, while a Set hassize. Mistake:mySet.lengthwill returnundefined.