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.

Answers:

Answer

Just another solution using Array.prototype.flat() and Array.prototype.map().

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

var result = array1.map(
   (element, index) => [element, array2[index]]
).flat();
Answer

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/

Answer

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/

Answer

Try something like this:-

 function merge(array1, array2) {
if (array1.length == array2.length) {
    var c = [];
    for (var i = 0; i < array1.length; i++) {
        c.push([array1[i], array2[i]]);
    }
    return c;
}
return null;

}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.