Reputation:
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?
Upvotes: 1
Views: 89
Reputation: 9691
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);
Upvotes: 2
Reputation: 1828
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.
Upvotes: 1