I am trying to study Array.reduce. And I was given the following task:
Input data:
const report = [
{
dateOfReport: "11-01-2021",
userId: "id1",
userMetric: { first_metric: 10, second_metric: 15 },
},
{
dateOfReport: "11-01-2021",
userId: "id2",
userMetric: { first_metric: 9, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
userId: "id1",
userMetric: { first_metric: 11, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
userId: "id2",
userMetric: { first_metric: 16, second_metric: 19 },
},
];
And I need to get this data in the output
const output = [
{
dateOfReport: "11-01-2021",
id1: { first_metric: 10, second_metric: 15 },
id2: { first_metric: 9, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
id1: { first_metric: 11, second_metric: 14 },
id2: { first_metric: 16, second_metric: 19 },
},
];
I tried to write some code, but I have no idea how to do it correctly. How can I solve this problem?
Code:
const result = report.reduce((acc, dataItem) => {
let outputArray = [];
if (dataItem) {
outputArray.push({ ...dataItem, date: dataItem.dateOfReport, [dataItem.userId]: dataItem.userMetric });
}
return outputArray;
});
return result;
-
Does this answer your question? How to group an array of objects by keyponury-kostek– ponury-kostek2021年11月16日 11:31:14 +00:00Commented Nov 16, 2021 at 11:31
-
With the reduce function, acc is the accumulator. Basicly an object, you can give an initial value and it is in your use through every iteration. You don't neeed temp arrays, like outputArray.hade– hade2021年11月16日 11:37:36 +00:00Commented Nov 16, 2021 at 11:37
1 Answer 1
Corrected the logic
const report = [
{
dateOfReport: "11-01-2021",
userId: "id1",
userMetric: { first_metric: 10, second_metric: 15 },
},
{
dateOfReport: "11-01-2021",
userId: "id2",
userMetric: { first_metric: 9, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
userId: "id1",
userMetric: { first_metric: 11, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
userId: "id2",
userMetric: { first_metric: 16, second_metric: 19 },
},
];
const result = report.reduce((acc, dataItem) => {
const node = acc.find(item => item.dateOfReport === dataItem.dateOfReport);
if (node) {
node[dataItem.userId] = dataItem.userMetric;
} else {
acc.push({ dateOfReport: dataItem.dateOfReport, [dataItem.userId]: dataItem.userMetric });
}
return acc;
}, []);
console.log(result);
answered Nov 16, 2021 at 11:37
Nitheesh
20.1k3 gold badges28 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js