# [Codewars - 7kyu解題] Merge two arrays 陣列交錯合併 ###### tags: `Codewars`,`7kyu`,`Javascript`,`Array`,`for-loop`,`Math.max()` > Javascript菜鳥紀錄Codewars解題過程 ## Instructions 題目 :link: https://www.codewars.com/kata/583af10620dda4da270000c5 :pushpin: **Instructions:** Write a function that combines two arrays by alternatingly taking elements from each array in turn. :bulb: **Examples:** [a, b, c, d, e], [1, 2, 3, 4, 5] becomes [a, 1, b, 2, c, 3, d, 4, e, 5] [1, 2, 3], [a, b, c, d, e, f] becomes [1, a, 2, b, 3, c, d, e, f] :bulb: **Points:** The arrays may be of different lengths, with at least one character/digit. One array will be of string characters (in lower case, a-z), a second of integers (all positive starting at 1). ## :memo: My Solution 我的解法 ```javascript= function mergeArrays(a, b) { var result = [] for(let i=0;i<a.length||i<b.length;i++){ if(i<a.length&&i<b.length){ result.push(a[i]); result.push(b[i]); console.log(result); }else if(i>=a.length){ result.push(b[i]); }else if(i>=b.length){ result.push(a[i]); } } return result; } ``` ## :memo: Solutions 其他更精簡的寫法 ```javascript= function mergeArrays(a, b) { var answer = []; for (i = 0; i < Math.max(a.length, b.length); i++){ if (i < a.length) {answer.push(a[i]);} if (i < b.length) {answer.push(b[i]);} } return answer; } ```