I asked a similar question here Transform an Array into an Object using .reduce(), however I am trying to find an alternative solution with findIndex.
This input data:
const reports = [
{
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 },
},
];
Output data must be:
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 similar code below, but I get duplicate data in the output. Can anyone help solve this problem?
const groupedReports = reports.reduce((acc, dataItem) => {
const nodeIndex = acc.findIndex((item) => item.dateOfReport === dataItem.dateOfReport);
const newNode = { date: dataItem.date, [dataItem.userId]: dataItem.userMetric };
console.log("NEW NODE", newNode);
return [...acc.slice(0, nodeIndex - 1), newNode, ...acc.slice(nodeIndex + 1)]
}, []);