combining 2 multi-dim arrays


M

mike

I have 2 multi-dimensional array I want to combine and I'm drawing a
blank on the "how"

var array1 = [
["1","a"],
["2","b"]
];

var array2 = [
["3","c"],
["4","d"]
];

These methods do not work:

var array3 = [
[array1],
[array2]
];

var array3 = [
array1,array2
];

array3 should look like this:

["1","a"],
["2","b"],
["3","c"],
["4","d"]

Any help is appreciated.

Mike
 
Ad

Advertisements

L

Lasse Reichstein Nielsen

mike said:
I have 2 multi-dimensional array I want to combine ....
var array1 = [
["1","a"],
["2","b"]
];

var array2 = [
["3","c"],
["4","d"]
]; .....
array3 should look like this:

["1","a"],
["2","b"],
["3","c"],
["4","d"]

Try
var array3 = array1.concat(array2);

/L
 
T

Thomas 'PointedEars' Lahn

mike said:
I have 2 multi-dimensional array I want to combine and I'm drawing a
blank on the "how"

var array1 = [
["1","a"],
["2","b"]
];

var array2 = [
["3","c"],
["4","d"]
];

These methods do not work:

var array3 = [
[array1],
[array2]
];

That evaluates to

var array3 = [[[["1","a"], ["2","b"]]], [[["3","c"], ["4","d"]]]];
var array3 = [
array1,array2
];

That evaluates to:

var array3 = [[["1","a"], ["2","b"]], [["3","c"], ["4","d"]]];
array3 should look like this:

["1","a"],
["2","b"],
["3","c"],
["4","d"]

Any help is appreciated.

Specific:

var array3 = [array1[0], array[1], array2[0], array2[1]];

General:

var array3 = array1.concat(array2);

(JavaScript 1.2 (NN4+), JScript 3.0 (IE4+), ECMAScript 3) or

var
a = [array1, array2],
array3 = [];

for (var i = 0, len = a.length; i < len; i++)
{
var o = a;
for (var j = 0, len2 = o.length; j < len2; j++)
{
array3.push(o[j]); // or: array3[array3.length] = o[j];
}
}

The following method helps to recognize that:

Array.prototype.toString = function()
{
return "[" + this.join(",") + "]";
}

Examples:

window.alert([array1, array2, array3].join("\n"));
window.alert([array1, array2, array1.concat(array2)].join("\n"));


HTH

PointedEars
 
Ad

Advertisements


Top