Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Two Arrays so that the Values Alternate

I'm looking for a jQuery method to merge two arrays so that their values alternate:

var array1 = [1,2,3,4,5];
var array2 = ['a', 'b', 'c', 'd', 'e'];

The result I want is:

var arrayCombined = [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e'];

Please note that I know it is trivial to do this in JS, however I am after a jQuery method that will do this.

like image 866
Undistraction Avatar asked Nov 06 '12 15:11

Undistraction


People also ask

How do you unify two arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do you merge two arrays using the spread Operator?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.

Which function combines for merge two or more arrays?

array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.


2 Answers

You can use the map method:

var array1 = [1, 2, 3, 4, 5];
var array2 = ['a', 'b', 'c', 'd', 'e'];

var arrayCombined = $.map(array1, function(v, i) {
  return [v, array2[i]];
});

console.log(arrayCombined);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Demo: http://jsfiddle.net/Guffa/hmUy6/

like image 61
Guffa Avatar answered Oct 27 '22 20:10

Guffa


If you must use jQuery, you can take advantage of their broken $.map implementation.

var result = $.map(array1, function(v, i) {
                                return [v, array2[i]];
                           });

jQuery's $.map flattens the returned array, giving you the result you want.

DEMO: http://jsfiddle.net/8rn2w/


Pure JS solution:

var result = array1.reduce(function(arr, v, i) {
                              return arr.concat(v, array2[i]); 
                           }, []);

DEMO: http://jsfiddle.net/8rn2w/1/

like image 27
I Hate Lazy Avatar answered Oct 27 '22 18:10

I Hate Lazy