I need to do some chart in Dygraph.js, with multiple series.
For example i have this dataset:
array1 = [ ['2016-03-16', 10,]
['2016-03-17', 20,]
['2016-03-19', 20,]
['2016-03-20', 15,]
];
array2 = [ ['2016-03-16', 30,]
['2016-03-18', 50,]
['2016-03-20', 30,]
];
And i want to merge this arrays into one:
merged = [ ['2016-03-16', 10, 30]
['2016-03-17', 20, null]
['2016-03-18', null, 50]
['2016-03-19', 20, null]
['2016-03-20', 15, 30,]
];
Ofcorse dates are in more complex format: YYYY-MM-DD HH:mm:ss
.
I'm using moment.js for dates operation.
How to merge these arrays in the fastest way?
A solution for any count of series.
var array1 = [['2016-03-16', 10], ['2016-03-17', 20], ['2016-03-19', 20], ['2016-03-20', 15]],
array2 = [['2016-03-16', 30], ['2016-03-18', 50], ['2016-03-20', 30]],
merged = function (array) {
var o = {}, r = [];
array.forEach(function (a, i) {
a.forEach(function (b) {
if (!o[b[0]]) {
o[b[0]] = Array.apply(null, { length: array.length + 1}).map(function () { return null; });
o[b[0]][0] = b[0];
r.push(o[b[0]]);
}
o[b[0]][i + 1] = b[1];
});
});
return r.sort(function (a, b) { return a[0].localeCompare(b[0]); });
}([array1, array2]);
document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');