1

Having an array intialized to a value, which would be the best way to merge to a second array over the first one?

var a = [[0,0,0,0], [0,0,0,0]]; // 2x4
var b = [[1,1], [2,2]];

For a simple dimension could be used:

var base = [0, 0, 0, 0, 0, 0, 0, 0];
var add = [1, 2, 3, 4];
for (i in add) {
    base[i] = add[i];
}

>>> base
[1, 2, 3, 4, 0, 0, 0, 0]

But how about 2 or 3 dimensions?

2 Answers2

2

Two dimensions:

for (i in add) {
    for (j in add[i])
        base[i][j] = add[i][j];
}

Three dimensions:

for (i in add) {
    for (j in add[i])
        for (k in add[i][j])
            base[i][j][k] = add[i][j][k];
}

etc.

For any number of dimensions you can solve the problem recursively:

function merge(source, destination){
  if (source[0] instanceof Array) {
    for (i in source) merge(source[i], destination[i]) // go deeper
  }  
  else {
    for (i in source) destination[i] = source[i];
  }
}

and you call it with : merge (add, base);

gabitzish
  • 9,535
  • 7
  • 44
  • 65
1

try this:

var mergeArr = function(arrFrom, arrTo) {
  for(var i=0;i<arrFrom.length; i++) {
    if (Array.isArray(arrFrom[i]) && Array.isArray(arrTo[i])) {
      mergeArr(arrFrom[i], arrTo[i]);
    } else {
      arrTo[i] = arrFrom[i];
    }
  }
}

Should work with any dimension you throw at it.

YS.
  • 1,808
  • 1
  • 19
  • 33
  • oh, please don't use `for..in` for array, use `for..var` instead: http://stackoverflow.com/questions/7223697/for-var-i-0-i-a-length-i-vs-for-var-i-in-a – YS. Apr 20 '12 at 11:52
  • The only problem is that the method *isArray* is not in the ECMAScript 3rd edition standard which is almost fully implemented in all current browsers. But I'm supposed that *Array.isArray* could be substituted by *arrFrom[i].length !== undefined* –  Apr 20 '12 at 12:15
  • I would've provided you w/ an answer around the absence of certain functions had you provided adequate info. – YS. Apr 20 '12 at 12:23