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 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Set the elements not added to undefined: [1, 2, 3, 4, undefined, undefined, undefined, undefined]
what are the inputs ? (base and add)
There was a little mistake in my code. I've written source[i] = destination[i] instead of destination[i] = source[i].
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.

3 Comments

oh, please don't use for..in for array, use for..var instead: stackoverflow.com/questions/7223697/…
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
I would've provided you w/ an answer around the absence of certain functions had you provided adequate info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.