เราจำเป็นต้องเขียนฟังก์ชันอาร์เรย์ JavaScript ที่รับอาร์เรย์ที่ซ้อนกันและส่งกลับอาร์เรย์ที่มีองค์ประกอบทั้งหมดที่มีอยู่ในอาร์เรย์โดยไม่มีการซ้อนกัน
ตัวอย่างเช่น −
//if the input is: const arr = [[1, 2, 3], [4, 5], [6]]; //then the output should be: const output = [1, 2, 3, 4, 5, 6];
ดังนั้น เรามาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
วิธีที่ 1:การใช้การเรียกซ้ำ
ที่นี่ เราจะวนรอบอาร์เรย์ที่ซ้อนกันดั้งเดิมและผลักองค์ประกอบที่ซ้อนกันไปยังอาร์เรย์ใหม่แบบเรียกซ้ำ
ตัวอย่าง
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:การใช้ Arrray.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 ]