ฟังก์ชันนี้รับอาร์เรย์จำนวนไม่จำกัด (variadic arguments) และรวมค่าทั้งหมดเข้าเป็นอาร์เรย์เดียว
ตัวอย่าง
// Input: [1, 5], [44, 67, 3], [2, 5], [7], [4], [3, 7], [6] // Output: [1, 5, 44, 67, 3, 2, 5, 7, 4, 3, 7, 6]
ตัวอย่างโค้ด
const a = [1, 5], b = [44, 67, 3], c = [2, 5], d = [7], e = [4], f = [3, 7], g = [6];
const concatArrays = (...arr) => {
// ใช้ reduce รวมอาร์เรย์ทั้งหมด
const res = arr.reduce((acc, val) => {
return acc.concat(...val);
}, []);
return res;
};
console.log(concatArrays(a, b, c, d, e, f, g));
เทคนิคที่ใช้
- Rest parameters (...arr) - รับอาร์เรย์จำนวนไม่จำกัด
- Array.reduce() - สะสมค่าจากอาร์เรย์แต่ละอัน
- Spread operator (...val) - แยกสมาชิกของอาร์เรย์ย่อยเพื่อ concat
ผลลัพธ์
[ 1, 5, 44, 67, 3, 2, 5, 7, 4, 3, 7, 6 ]
ทางเลือกอื่น: สามารถใช้ arr.flat() ได้ในรุ่น JavaScript ใหม่ๆ (ES2019+)