-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgroubBy.js
57 lines (46 loc) · 1.25 KB
/
groubBy.js
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
const timesheetEntries = [
{
joiningDate: '2011-01-08',
project: 'CTRF',
designation: 'Manager'
},
{
date: '2024-01-09',
project: 'CTRF',
designation: 'Developer'
},
{
date: '2024-01-10',
project: 'CTRF',
designation: 'Tester'
},
];
// Grouping by 'project' property using reduce
const groupedByReduce = timesheetEntries.reduce((previousValue, currentValue) => {
const key = currentValue.project;
if (!previousValue[key]) {
previousValue[key] = [];
}
previousValue[key].push(currentValue);
return previousValue;
}, {});
console.log(groupedByReduce);
const groupedByObject = Object.groupBy(timesheetEntries, (entries, index) => {
return entries.project;
});
console.log(groupedByObject);
const groupedByMap = Map.groupBy(timesheetEntries, (entries, index) => {
return entries.project;
});
console.log(groupedByMap);
// LeetCode - https://leetcode.com/problems/group-by/
// Array.prototype.groupBy = function (fn) {
// return this.reduce((acc, curr) => {
// const key = fn(curr)
// if (!acc[key]) {
// acc[key] = [];
// }
// acc[key]?.push(curr);
// return acc;
// }, {});
// };