1

我在 JavaScript 中有以下两个数组:

"total":[[1370923200000,"66"],[1371009600000,"42"],[1371096000000,"23"]]

"successful":[[1370923200000,"5"],[1371096000000,"2"],[1371182400000,"0"]]

我想将它们组合成一个数组/对象,看起来像这样:

{date:1370923200000, total:"66", successful:"5"},
{date:1371009600000, total:"42"},
{date:1371096000000, total:"23", successful:"2"},
{date:1371182400000, successful:"0"}

我尝试了多种不同的解决方案,遍历两个数组,但我似乎无法找到一个优雅的解决方案。

4

3 回答 3

1

在这里你有:

var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
var successful = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
var combined = {};

for(var i=0; i<total.length; i++){
    combined[total[i][0]] = {date: total[i][0], total: total[i][1]};
}

for(var i=0; i<successful.length; i++){
    if(successful[i][0] in combined){
        combined[successful[i][0]].successful = successful[i][1];
    }
    else{
        combined[successful[i][0]] = {
            date: successful[i][0], successful: successful[i][1]
        };
    }
}

var result = [];
for(var key in combined){
    result.push(combined[key]);
}
alert(result.toSource());

还有一个工作小提琴http://jsfiddle.net/eRjeZ/

于 2013-07-11T15:03:54.127 回答
0
var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
var succes = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
var everything = {}; 
var output = [];

total.map(  function( item ){ addToEverything( item , "total" ) } );
succes.map( function( item ){ addToEverything( item , "successful" ) } );

console.log( everything ); // This looks 'like' what you want, but better

for( var key in everything )
  output.push( everything[key] );

console.log( output ); //This looks exactly like what you want

function addToEverything( item , name )
{
  var key = item[0];
  var entry = everything[key] || { date : key };
  entry[name] = item[1];
  everything[key] = entry; 
}
于 2013-07-11T17:05:48.480 回答
0

n 个数组的简单解决方案:

var arrays = {"total":[…], "successful":[…]};

var result = [];
for (var prop in arrays) {
    var arr = arrays[prop];
    var i=0;
    for (var j=0; j<arr.length; j++) {
        var date = arr[j][0];
        while (i < result.length && date > result[i].date) i++;
        if (i < result.length && date == result[i].date) {
            result[i][prop] = arr[j][1];
        } else {
            var o = {date:date};
            o[prop] = arr[j][1];
            result.splice(i, 0, o);
        }
    }
}

如果您需要更快,您可以使用Multiple Array Merge Using Binary Heap(另请参阅Algorithm for N-way merge)。如果您只有两个列表,请查看最有效的方法来合并两个对象数组

于 2013-07-11T15:04:07.047 回答