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

Is there a way to efficiently "pivot" a multidimensional array?

I have an array of arrays formatted the following way:

[['BTC', '2022-04-27', '39151.53'],
 ['BTC', '2022-04-26', '37730.20'],
 ['BTC', '2022-04-25', '39151.53'],
 ['ETH', '2022-04-27', '39151.53'],
 ['ETH', '2022-04-26', '37730.20'],
 ['ETH', '2022-04-25', '39151.53']]

What I would like to end up with is:

[['Date', 'BTC, 'ETH'],
 ['2022-04-27', '39151.53', '39151.53'],
 ['2022-04-26', '37730.20', '39151.53'],
 ['2022-04-25', '39151.53', '39151.53']]

Is there any non-complicated way to solve it?

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

>Solution :

It looks like the OP needs the inner arrays indexed by the date field. This can be done with reduce. Once there’s an index, walk through the keys (dates) and collect the values associated with each date.

const array = [['BTC', '2022-04-27', '39151.53'],
 ['BTC', '2022-04-26', '37730.20'],
 ['BTC', '2022-04-25', '39151.53'],
 ['ETH', '2022-04-27', '39151.53'],
 ['ETH', '2022-04-26', '37730.20'],
 ['ETH', '2022-04-25', '39151.53']];

const dateIndex = array.reduce((acc, a) => {
  let date = a[1];
  if (!acc[date]) acc[date] = [];
  acc[date].push(a);
  return acc;
}, {});


let result = [['Date', 'BTC', 'ETH']];
Object.keys(dateIndex).map(date => {
  let values = dateIndex[date].map(arr => arr[2]);
  result.push([date, ...values]);
});

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