我在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"}
我尝试了多种不同的解决方案,循环遍历两个阵列,但我似乎无法找到一个优雅的解决方案。
答案 0 :(得分: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/
答案 1 :(得分: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)。如果您只有两个列表,请查看Most efficient way to merge two arrays of objects。
答案 2 :(得分: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;
}