1

I wish to merge two arrays into one, but cant duplicate using datetime, basically cant merge two results from both arrays with the same datetime.

  • In each array, the datetime is never repeated.
  • Both arrays have the same structure, with the same exact positions.
  • Each array have +60 sub arrays.

example:

Array1 = [[a,b,0000-00-00 00:00],[c,d,0000-00-00 00:59],[e,f,0000-00-00 00:10]];
Array2 = [[z,x,0000-00-00 00:00],[h,s,0000-00-00 00:49],[e,f,0000-00-00 00:20]];


Array12 = [[a,b,0000-00-00 00:00],[c,d,0000-00-00 00:59],[e,f,0000-00-00 00:10],[h,s,0000-00-00 00:49],[e,f,0000-00-00 00:20]];

How can i make this work? I tried a lot of functions, but cant get this working.

Thanks.

azost
  • 571
  • 11
  • 22
  • 1
    Duplicate http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript Also, you need `"` or `'` around your data. Fiddle: http://jsfiddle.net/U7f5j/ – verbanicm Jul 25 '13 at 15:18

1 Answers1

2

If I'm correct you are trying to merge the arrays based in timestamps. Try out this fiddle

var Array1 = [
    ['a', 'b', '0000-00-00 00:00'],
    ['c', 'd', '0000-00-00 00:59'],
    ['e', 'f', '0000-00-00 00:10']
];
var Array2 = [
    ['z', 'x', '0000-00-00 00:00'],
    ['h', 's', '0000-00-00 00:49'],
    ['e', 'f', '0000-00-00 00:20']
];

function mergeArrays(arr1, arr2) {
    var merger = {};

    for (var i = 0; i < arr1.length; i++) {
        merger[arr1[i][2]] = [arr1[i][0], arr1[i][1], arr1[i][2]];
    }

    for (var i = 0; i < arr2.length; i++) {
        if (!(arr2[i][2] in merger)) {
            merger[arr2[i][2]] = [arr2[i][0], arr2[i][1], arr2[i][2]];
        }
    }

    var output = [];
    for (var key in merger) {
        output.push(merger[key]);
    }
    return output;
}

var result = mergeArrays(Array1, Array2);
console.log(result);
Siddhartha Gupta
  • 1,140
  • 8
  • 13
  • Thanks, everything is working great even in much bigger arrays! Just a little typo in _if (!(arr2[i][2] in combined)) {_ , replacing **combined** with **merger** fix it. – azost Jul 25 '13 at 19:34