-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupBy.js
More file actions
79 lines (59 loc) · 1.69 KB
/
Copy pathGroupBy.js
File metadata and controls
79 lines (59 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Ask by TRUEIGTECH Company (23-05-2026)
// Q. you need to make a group of this array department wise
// A. {
// Engineering: [
// { id: 1, name: "Aashima", department: "Engineering" },
// { id: 3, name: "Rahul", department: "Engineering" }
// ],
// Design: [
// { id: 2, name: "Muskan", department: "Design" },
// { id: 5, name: "Neha", department: "Design" }
// ],
// HR: [
// { id: 4, name: "Priya", department: "HR" }
// ]
// }
const users = [
{ id: 1, name: "Aashima", department: "Engineering", },
{ id: 2, name: "Muskan", department: "Design" },
{ id: 3, name: "Rahul", department: "Engineering", },
{ id: 4, name: "Priya", department: "HR" },
{ id: 5, name: "Neha", department: "Design" }
];
// Solutions 1:
// used - Custom Logic
function solution1(users) {
let obj = {};
for (let ele of users) {
if (Object.keys(obj).includes(ele.department)) {
obj[ele.department].push(ele);
} else {
obj[ele.department] = [ele];
}
};
return obj;
}
const result1 = solution1(users);
console.log('result1 => ', result1)
// Solutions 2:
// used in-built Object.groupBy() method
function solution2(users) {
return Object.groupBy(users, (ele) => ele.department);
}
const result2 = solution2(users);
console.log('result2 => ', result2)
// Solutions 3:
// Different Custom Logic
function solution3(users) {
let obj = {};
for (let ele of users) {
let department = ele.department;
if (!obj[department]) {
obj[department] = []
}
obj[department].push(ele);
}
return obj;
}
const result3 = solution3(users);
console.log('result3 => ', result3)