2

i am trying to merge 2 array of Date objects uniqely, but don't get it the decent way. Here is my noob solution:

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

This works, but it seems to be kinda nooby and i guess inperformat too? Another try i made was this:

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

But this does not work at all. How to do it correctly and performant?

Tino
  • 33
  • 5
  • Don't use for-in-loops on arrays – Bergi Jul 25 '12 at 11:23
  • Even with a typical for loop i cannot get it. The matches are detected, but the splice seems to fail. – Tino Jul 25 '12 at 16:10
  • possible duplicate of [How to merge two arrays in Javascript](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript) or [Easiest way to find duplicate values in a JavaScript array](http://stackoverflow.com/q/840781/1048572) – Bergi Jul 25 '12 at 16:17

1 Answers1

3

This should work, assuming you want them ordered:

$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]);
    }
}    

Some of this code was taken from here, just in case you need more depth into the sorting

Community
  • 1
  • 1
Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • Sorting on Date objects fails. Thats why for some reason this solution does not work. I'm yet investigating and would appreciate any suggestion that may improve or solve my problem. – Tino Jul 25 '12 at 16:14