Skip to content

Commit 8c5fa66

Browse files
committed
[LES-3.1/compl] intro-to-set-obj
Practice with "new Set(), has() & filter/map(), [...spread]". Worth noting: - all this lesson/practice (note the solutions). FS-dev: B-4 / JS advanced
1 parent d3beeb9 commit 8c5fa66

File tree

1 file changed

+88
-1
lines changed
  • full-stack-dev/4-js-advanced/3-set-and-map/3-1-intro-to-set-obj

1 file changed

+88
-1
lines changed
Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,91 @@
11
'use strict';
22

33
// Задание 1:
4-
//
4+
// Напиши функцию uniqueTags(tags), которая принимает массив и возвращает новый массив, содержащий только уникальные теги.
5+
6+
const rawTags = ['js', 'css', 'html', 'js', 'css', 'react'];
7+
8+
function uniqueTags(tags) {
9+
if (!tags || !Array.isArray(tags)) {
10+
return [];
11+
}
12+
13+
return [...new Set(tags)];
14+
}
15+
16+
console.log(uniqueTags(rawTags)); // [ 'js', 'css', 'html', 'react' ]
17+
18+
// Задание 2:
19+
// Напиши функцию filterUsers(users, bannedIds), которая вернет массив пользователей без тех, кто находится в черном списке.
20+
// Важное условие: Для проверки блокировки используй Set, чтобы поиск был максимально быстрым (представим, что bannedIds может быть очень большим).
21+
// Подсказка: тебе понадобится метод filter для массива пользователей и метод has для множества забаненных ID.
22+
23+
const users = [
24+
{ id: 1, name: 'Max' },
25+
{ id: 2, name: 'Kate' }, // забанена
26+
{ id: 3, name: 'Leo' },
27+
{ id: 4, name: 'Alex' }, // забанен
28+
];
29+
30+
const bannedIds = [2, 4];
31+
32+
function filterUsers(users, bannedIds) {
33+
if (!users || !Array.isArray(users)) {
34+
return [];
35+
}
36+
37+
if (!bannedIds || !Array.isArray(bannedIds)) {
38+
return [];
39+
}
40+
41+
const bannedIdsSet = new Set(bannedIds);
42+
43+
return users.filter((user) => !bannedIdsSet.has(user.id));
44+
}
45+
46+
console.log(filterUsers(users, bannedIds)); // [ { id: 1, name: 'Max' }, { id: 3, name: 'Leo' } ]
47+
48+
// Задание 3:
49+
// Напиши функцию findCommonEmployees(dept1, dept2), которая вернет массив имен, встречающихся в обоих списках.
50+
// Совет: Здесь логика похожа на предыдущую задачу, но «наоборот». Тебе нужно оставить тех, кто есть в Set, а не тех, кого нет.
51+
52+
const frontend = ['Alice', 'Bob', 'Charlie', 'Dan'];
53+
const backend = ['Bob', 'Dan', 'Eve', 'Frank'];
54+
55+
function findCommonEmployees(dept1, dept2) {
56+
if (!dept1 || !Array.isArray(dept1)) {
57+
return [];
58+
}
59+
60+
if (!dept2 || !Array.isArray(dept2)) {
61+
return [];
62+
}
63+
64+
const dept2Set = new Set(dept2);
65+
66+
return dept1.filter((name) => dept2Set.has(name));
67+
}
68+
69+
console.log(findCommonEmployees(frontend, backend)); // [ 'Bob', 'Dan' ]
70+
71+
// Задание 4:
72+
// Напиши функцию getUniqueCategories(orders), которая вернет массив строк: ['food', 'electronics', 'clothing'].
73+
// Подсказка: Нельзя просто засунуть объекты в Set. Тебе нужно сначала «достать» категории. Попробуй скомбинировать методы массива (map) и Set.
74+
75+
const orders = [
76+
{ id: 1, category: 'food', price: 100 },
77+
{ id: 2, category: 'electronics', price: 500 },
78+
{ id: 3, category: 'food', price: 200 },
79+
{ id: 4, category: 'clothing', price: 50 },
80+
{ id: 5, category: 'electronics', price: 600 },
81+
];
82+
83+
function getUniqueCategories(orders) {
84+
if (!orders || !Array.isArray(orders)) {
85+
return [];
86+
}
87+
88+
return [...new Set(orders.map((order) => order.category))];
89+
}
90+
91+
console.log(getUniqueCategories(orders)); // [ 'food', 'electronics', 'clothing' ]

0 commit comments

Comments
 (0)