Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform an Array into an Object using .reduce()

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading