将两个日期系列合并为一个

Merge two dates series into one

我需要在 Dygraph.js 中制作一些包含多个系列的图表。

例如我有这个数据集:

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 = [ ['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,]
         ];

当然日期的格式更复杂:YYYY-MM-DD HH:mm:ss。 我正在使用 moment.js 进行日期操作。

如何以最快的方式合并这些数组?

这样做:

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,]
         ];

//get the bigger array
var src = array1.length > array2.length ? array1 : array2;
//get the smaller array
var dest = array1.length > array2.length ? array2 : array1;
//iterate the bigger array
var final = src.map(function(array){
    var date = array[0];
    //find in smaller array
    var filtered = dest.filter(function(d){
        return d[0] == date;
    });
    var thirdData= null;
    if (filtered.length > 0){
      //iff filtered get the first record
        thirdData = filtered[0][1]
    }
    return [date, array[1], thirdData]
})
console.log(final);

工作代码here

任意数量系列的解决方案。

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>');