เราต้องเขียนฟังก์ชันอาร์เรย์ของ JavaScript ที่รับอาร์เรย์ซ้อน (nested array) และคืนค่าอาร์เรย์ที่มีองค์ประกอบทั้งหมดโดยไม่มีการซ้อนกัน
ตัวอย่างเช่น:
// หากอินพุตคือ: const arr = [[1, 2, 3], [4, 5], [6]]; // ผลลัพธ์ควรเป็น: const output = [1, 2, 3, 4, 5, 6];
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน:
วิธีที่ 1: ใช้ Recursion
เราจะวนลูปผ่านอาร์เรย์ซ้อนต้นฉบับและเพิ่มองค์ประกอบซ้อนเข้าไปในอาร์เรย์ใหม่แบบเรียกซ้ำ
ตัวอย่างโค้ด
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function() {
let res = [];
for (let i = 0; i < this.length; i++) {
if (Array.isArray(this[i])) {
res.push(...this[i].flatten());
} else {
res.push(this[i]);
}
}
return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());
วิธีที่ 2: ใช้ Array.prototype.reduce()
เราจะใช้ reduce() เพื่อสร้างอาร์เรย์ใหม่แบบนี้:
ตัวอย่างโค้ด
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function() {
return this.reduce((acc, val) => {
return acc.concat(...val);
}, []);
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());
ผลลัพธ์
ผลลัพธ์ในคอนโซลสำหรับทั้งสองวิธีจะเป็นดังนี้:
[ 1, 2, 3, 4, 5, 6 ]