3

I have two arrays in javascript:

var array1 = ["a","b","c"];
var array2 = ["e","f","g"];

And I want the resulting array to be like this:

array3 = ["a","e","b","f","c","g"];

Any way to do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
salamey
  • 3,633
  • 10
  • 38
  • 71

3 Answers3

7

Will a straightforward loop do it?

array3 = new Array();

for(var i = 0; i < array1.length; i++)
{
    array3.push(array1[i]);
    array3.push(array2[i]);
}
Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
3

You can try with concat() method:

var array1 = ["a","b","c"];
var array2 = ["e", "f","g"];

var array3 = array1.concat(array2); // Merges both arrays

For your specific requirement, you have to follow this:

function mergeArrays(a, b){
    var ret = [];

    for(var i = 0; i < a.length; i++){
        ret.push(a[i]);
        ret.push(b[i]);
    }
    return ret;
}
Santosh Panda
  • 7,235
  • 8
  • 43
  • 56
3

This should work:

function zip(source1, source2){
    var result=[];
    source1.forEach(function(o,i){
       result.push(o);
       result.push(source2[i]);
    });
    return result
}

Look http://jsfiddle.net/FGeXk/

It was not concatenation, so the answer changed.

Perhaps you would like to use: http://underscorejs.org/#zip

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43