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

What would be an efficient algo in JavaScript to merge date time series?

I have the following time series list as input:

const ts1 = [
  ['2023-01-20', 1],
  ['2023-01-21', 2],
  ['2023-01-22', 3],
  ['2023-01-23', 4],
];

const ts2 = [
  ['2023-01-18', 5],
  ['2023-01-19', 6],
  ['2023-01-20', 7],
  ['2023-01-21', 8]
];

const ts3 = [
  ['2023-01-21', 9],
  ['2023-01-22', 10],
  ['2023-01-23', 11],
  ['2023-01-24', 12]
];

I’d like the output to be the merged (column stacked) version like so:

const output = [
  ['2023-01-18', null,    5, null],
  ['2023-01-19', null,    6, null],
  ['2023-01-20',    1,    7, null],
  ['2023-01-21',    2,    8,    9],
  ['2023-01-22',    3, null,   10],
  ['2023-01-23',    4, null,   11],
  ['2023-01-24', null, null,   12]
];

To give a bit more context, I’m reusing a REST API which provides the individual time-series and I need to compile the AnyChart required tableData format.

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 :

I’d go with something like

const merged = {};

let tses = [ts1, ts2, ts3];
for (let i = 0; i < tses.length; i++) {
  for (const [t, v] of tses[i]) {
    if (!merged[t]) merged[t] = new Array(tses.length).fill(null);
    merged[t][i] = v;
  }
}

console.log(Object.entries(merged).map(([t, vs]) => [t, ...vs]));

This outputs

[
  [ '2023-01-20', 1, 7, null ],
  [ '2023-01-21', 2, 8, 9 ],
  [ '2023-01-22', 3, null, 10 ],
  [ '2023-01-23', 4, null, 11 ],
  [ '2023-01-18', null, 5, null ],
  [ '2023-01-19', null, 6, null ],
  [ '2023-01-24', null, null, 12 ]
]

as expected.

For sorted order (since the keys are lexicographically sortable), do

console.log(Object.keys(merged).sort().map(key => [key, ...merged[key]]));

instead:

[
  [ '2023-01-18', null, 5, null ],
  [ '2023-01-19', null, 6, null ],
  [ '2023-01-20', 1, 7, null ],   
  [ '2023-01-21', 2, 8, 9 ],      
  [ '2023-01-22', 3, null, 10 ],  
  [ '2023-01-23', 4, null, 11 ],
  [ '2023-01-24', null, null, 12 ]
]
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