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?

6
  • Have you tried anything yourself yet?
    – Sirko
    Commented May 31, 2013 at 7:37
  • Would that be the same stackoverflow.com/questions/4874818/… ?
    – Michael
    Commented May 31, 2013 at 7:38
  • What you want is not concatenation. You have confused at least four people with that title (three answerers and me). Commented May 31, 2013 at 7:42
  • Sorry I thought it counted as a concatenation too... I don't know the right word for what I want
    – salamey
    Commented May 31, 2013 at 7:45
  • 1
    it is "zip" zipping 2 arrays Commented May 31, 2013 at 7:49

3 Answers 3

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]);
}
1
  • 1
    Answer could be more robust, if you have different length arrays for instance. Commented Dec 8, 2021 at 0:40
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;
}
3
  • 8
    This will result in the wrong order of elements!
    – Sirko
    Commented May 31, 2013 at 7:39
  • 1
    This is not what I need, please see the example in my question
    – salamey
    Commented May 31, 2013 at 7:42
  • 1
    I have updated my answer as per your requirement. Commented May 31, 2013 at 7:53
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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.