Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  73] [ 6]  / answers: 1 / hits: 22836  / 12 Years ago, tue, november 6, 2012, 12:00:00

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.


More From » jquery

 Answers
27

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/


[#82157] Monday, November 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;