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? Commented May 31, 2013 at 7:37
  • Would that be the same stackoverflow.com/questions/4874818/… ? 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 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]); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Answer could be more robust, if you have different length arrays for instance.
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 Comments

This will result in the wrong order of elements!
This is not what I need, please see the example in my question
I have updated my answer as per your requirement.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.