2

我正在尝试唯一地合并 2 个 Date 对象数组,但不要以正确的方式获得它。这是我的菜鸟解决方案:

$old = [new Date('2012-08-01'), new Date('2012-08-02'), new Date('2012-08-03')];
$new = [new Date('2012-08-01'), new Date('2012-08-06')];

$old2 = $.map($old, function(el, idx) {
   for (var i in $new)
   {
      if ($new[i].getTime() == el.getTime()) return null;
   }
   return el;
});

$new2 = $.map($new, function(el, idx) {
   for (var i in $old)
   {
      if ($old[i].getTime() == el.getTime()) return null;
   }
   return el;
});

$final = $.merge($old2, $new2);

这行得通,但它似乎有点笨拙,我猜也是inperformat?我做的另一个尝试是这样的:

for (var i in $new)
{
   var found = false;

   for (var j in $old)
   {
      if ($old[j].getTime() == $new[i].getTime())
      {
         found = true;
         $old = $old.splice(j, 1);
      }
   }

   if (found)
   {
      $new = $new.splice(i, 1);
   }
}

$final = $.merge($old, $new);

但这根本不起作用。如何正确和高效地做到这一点?

4

1 回答 1

3

这应该有效,假设您希望它们订购:

$old = [new Date('2012-08-01'), new Date('2012-08-02'), new Date('2012-08-03')];
$new = [new Date('2012-08-01'), new Date('2012-08-06')];

var second = $old.concat($new);
var sorted_second = second.sort(); // You can define the comparing function here. 
                         // JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < second.length - 1; i++) {
    if (sorted_second[i + 1] != sorted_second[i]) {
        results.push(sorted_second[i]);
    }
}    

其中一些代码取自这里,以防您需要更深入的排序

于 2012-07-25T10:49:08.993 回答