-1
var arrayOne = [a,b,c];  
var arrayTwo = [d,e,f]; 

How can I combine the two arrays in JavaScript so that the result will be:

var array = [a,d,b,e,c,f];

Note: This is not concatenating two arrays. This is merging the two arrays so the indices look like [0,0,1,1,2,2].

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • var arrayTre = arrayOne.concat(arrayTwo ); – ale Sep 16 '14 at 11:05
  • apologies - the edit has clarified. You'd be looking for something like underscore.js's `_.zip` function. – Alnitak Sep 16 '14 at 11:11
  • I do not agree to these downvotes! +1 because of unnecessary downvoting. She did not say that she wanted to concatenate arrays. Even if she did it wouldn't be a reason to downvote. – Noel Widmer Sep 16 '14 at 11:12
  • @NoelWidmer not that I've down voted, but to be fair this is still an extremely elementary question. – Alnitak Sep 16 '14 at 11:13
  • 2
    +1 This question is a good example showcasing how many people (even high rep) don't read questions thoroughly enough, but are quick to vote and close. – Matt Way Sep 16 '14 at 11:14
  • @Alnitak Indeed it is. But people can mark as duplicate if there is an equivalent. Downvoting shouldn't be used for marking elementary questions. – Noel Widmer Sep 16 '14 at 11:46

2 Answers2

1

Assuming that the two arrays are equal of length, this should do the trick:

var arrayThree = [];
for(var i = 0; i < arrayOne.length; i++){
   arrayThree.push(arrayOne[i], arrayTwo[i]);
}

If they aren't the same length and you would have the two arrays:

var a = [a,b,c,d];
var b = [e,f];

I assume you would want the the following result

var c = [a,e,b,f,c,d];

That should do the trick:

var c = [];
while(Math.min(a.length, b.length)){
   c = c.concat(a.splice(0,1), b.splice(0,1));
   //Or c = c.concat(b.splice(0,1), a.splice(0,1));
   //depending on the order
}
a.length ? c = c.concat(a) : c = c.concat(b);
//Here is a = [c,d] and b = []
Eiiki
  • 310
  • 1
  • 3
  • 10
-1

You can use jQuery's unique method along with concat

var a = [1,2,3];
var b = [2,3,4];
var c = a.concat(b); // [1,2,3,2,3,4]
c = $.unique(c); // [1, 2, 3, 4]

You may need to sort the array as needed.

ChaseVoid
  • 5
  • 3
  • This does not address the question since it's about combining arrays and not about uniqueness of to concatenated arrays. – axelduch Sep 16 '14 at 12:45