This function is designed to merge arrays of any length:
var combineArrays = function () {
var resultArray = [],
allArgs = resultArray.slice.call(arguments),
maxLength = 0;
for (var index = 0, argLength = allArgs.length; index < argLength; index++) {
maxLength = allArgs[index].length > maxLength ? allArgs[index].length : maxLength;
}
for (index = 0; index < maxLength; index++) {
for (var j = 0; j < argLength; j++) {
var elementValue = allArgs[j][index];
if (elementValue) {
resultArray.push(elementValue);
}
}
}
return resultArray;
};
Example given:
var array1 = [1,2,3,4];
var array2 = ['a','b','c','d','e','f','g','h','i','j','k','l'];
var array3 = ['!','@','#','$','%','^','&','*','('];
combineArrays(array1, array2, array3);
// outcome: [1, "a", "!", 2, "b", "@", 3, "c", "#", 4, "d", "$", "e", "%", "f", "^", "g", "&", "h", "*", "i", "(", "j", "k", "l"]
This more concise approach would also work:
var combineArrays = function () {
var resultArray = [],
allArgs = resultArray.slice.call(arguments),
maxLength = Math.max.apply(null, allArgs.map(function (argument) { return argument.length; }));
for (index = 0; index < maxLength; index++) {
for (var j = 0, len = allArgs.length; j < len; j++) {
var elementValue = allArgs[j][index];
if (elementValue) {
resultArray.push(elementValue);
}
}
}
return resultArray;
};