Skip to content

Commit c7be1e2

Browse files
committed
[HW-3.13/st-compl] unique-arr-of-objects
Organizing uniqueness of arr/obj's, using Set/Map(), map/find() meth's. Worth noting: - all this work (alternative solution). FS-dev: B-4 / JS advanced
1 parent 5d46140 commit c7be1e2

File tree

1 file changed

+30
-0
lines changed
  • full-stack-dev/4-js-advanced/3-set-and-map/3-13-hw-1-unique-arr-of-objects

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Нужно сделать с помощью Set() уникализацию массива объектов:
2+
// Момент: Прямая уникализация объектов с помощью Set() невозможна.
3+
// - Необходимо уникализировать массив, содержащий объекты с идентичными идентификаторами (например, ID1, ID2, повторно ID1), удаляя повторяющиеся идентификаторы.
4+
// - Используем комбинацию `Set` с другими методами, такими как `map` и `find`, для обхода ограничений `Set` по отношению к объектам.
5+
6+
'use strict';
7+
8+
const users = [
9+
{ id: 1, name: 'Вася' },
10+
{ id: 2, name: 'Петя' },
11+
{ id: 1, name: 'Вася' },
12+
];
13+
14+
const usersSet = [...new Set(users.map((user) => user.id))].map((id) =>
15+
users.find((user) => user.id === id)
16+
);
17+
18+
console.log(usersSet); // [ { id: 1, name: 'Вася' }, { id: 2, name: 'Петя' } ]
19+
20+
// ?? альтернативное решение, через Map() (с линейной сложностью O(N))
21+
const usersMap = new Map();
22+
23+
for (const user of users) {
24+
if (!usersMap.has(user.id)) {
25+
usersMap.set(user.id, user);
26+
}
27+
}
28+
29+
const usersMapResult = Array.from(usersMap.values());
30+
console.log(usersMapResult); // [ { id: 1, name: 'Вася' }, { id: 2, name: 'Петя' } ]

0 commit comments

Comments
 (0)