เราต้องเขียนฟังก์ชันที่รับอาร์เรย์สองตัวและรวมกันโดยสลับสมาชิกจากแต่ละอาร์เรย์
ตัวอย่าง หากอาร์เรย์สองตัวคือ:
const arr1 = [4, 3, 2, 5, 6, 8, 9]; const arr2 = [2, 1, 6, 8, 9, 4, 3];
ผลลัพธ์ควรเป็น:
const output = [4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3];
ตัวอย่าง
โค้ดต่อไปนี้เป็นตัวอย่าง:
const arr1 = [4, 3, 2, 5, 6, 8, 9];
const arr2 = [2, 1, 6, 8, 9, 4, 3];
const mergeAlernatively = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length + arr2.length; i++){
if(i % 2 === 0){
res.push(arr1[i/2]);
}else{
res.push(arr2[(i-1)/2]);
};
};
return res;
};
console.log(mergeAlernatively(arr1, arr2));ผลลัพธ์
จะแสดงผลในคอนโซลดังนี้:
[ 4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3 ]