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.
3
Answers
I’d go with something like
This outputs
as expected.
For sorted order (since the keys are lexicographically sortable), do
instead:
An alternative method with
Array#reduce
and nullish coalescing assignment:You can create an efficient algorithm to merge the time series by first putting all the dates and values in a hash map and then converting it into an array.
This is an efficient approach because hash map operations (insertion and lookup) are generally O(1), which makes the algorithm faster than directly comparing and inserting into arrays.
Here is an example: