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?
>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)