I am trying to study Array.reduce
. And I was given the following task:
Input data:
JavaScript
x
23
23
1
const report = [
2
{
3
dateOfReport: "11-01-2021",
4
userId: "id1",
5
userMetric: { first_metric: 10, second_metric: 15 },
6
},
7
{
8
dateOfReport: "11-01-2021",
9
userId: "id2",
10
userMetric: { first_metric: 9, second_metric: 14 },
11
},
12
{
13
dateOfReport: "12-01-2021",
14
userId: "id1",
15
userMetric: { first_metric: 11, second_metric: 14 },
16
},
17
{
18
dateOfReport: "12-01-2021",
19
userId: "id2",
20
userMetric: { first_metric: 16, second_metric: 19 },
21
},
22
];
23
And I need to get this data in the output
JavaScript
1
13
13
1
const output = [
2
{
3
dateOfReport: "11-01-2021",
4
id1: { first_metric: 10, second_metric: 15 },
5
id2: { first_metric: 9, second_metric: 14 },
6
},
7
{
8
dateOfReport: "12-01-2021",
9
id1: { first_metric: 11, second_metric: 14 },
10
id2: { first_metric: 16, second_metric: 19 },
11
},
12
];
13
I tried to write some code, but I have no idea how to do it correctly. How can I solve this problem?
Code:
JavaScript
1
12
12
1
const result = report.reduce((acc, dataItem) => {
2
let outputArray = [];
3
4
if (dataItem) {
5
outputArray.push({ dataItem, date: dataItem.dateOfReport, [dataItem.userId]: dataItem.userMetric });
6
}
7
8
return outputArray;
9
});
10
11
return result;
12
Advertisement
Answer
Corrected the logic
JavaScript
1
33
33
1
const report = [
2
{
3
dateOfReport: "11-01-2021",
4
userId: "id1",
5
userMetric: { first_metric: 10, second_metric: 15 },
6
},
7
{
8
dateOfReport: "11-01-2021",
9
userId: "id2",
10
userMetric: { first_metric: 9, second_metric: 14 },
11
},
12
{
13
dateOfReport: "12-01-2021",
14
userId: "id1",
15
userMetric: { first_metric: 11, second_metric: 14 },
16
},
17
{
18
dateOfReport: "12-01-2021",
19
userId: "id2",
20
userMetric: { first_metric: 16, second_metric: 19 },
21
},
22
];
23
const result = report.reduce((acc, dataItem) => {
24
const node = acc.find(item => item.dateOfReport === dataItem.dateOfReport);
25
if (node) {
26
node[dataItem.userId] = dataItem.userMetric;
27
} else {
28
acc.push({ dateOfReport: dataItem.dateOfReport, [dataItem.userId]: dataItem.userMetric });
29
}
30
return acc;
31
}, []);
32
33
console.log(result);