ฟังก์ชัน Reursive สำหรับรวมค่าทุกตัวในอาร์เรย์ซ้อน (nested array) ให้กลายเป็นสตริงเดียว โดยเรียงลำดับตามลำดับที่ปรากฏ
ตัวอย่างโค้ด
const arr = [
'hello', [
'world', 'how', [
'are', 'you', [
'without', 'me'
]
]
]
];
const arrayToString = (arr) => {
let str = '';
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
str += arrayToString(arr[i]);
} else {
str += arr[i];
}
}
return str;
};
console.log(arrayToString(arr));
ผลลัพธ์
helloworldhowareyouwithoutme
วิธีแบบสมัยใหม่ (ES2019+)
// ใช้ flat() แล้ว join()
const result = arr.flat(Infinity).join('');
// หรือใช้ reduce
const result2 = arr.flat(Infinity).reduce((a, b) => a + b, '');
flat(Infinity) จะทำให้อาร์เรย์แบน (flatten) ลงลึกไม่จำกัดระดับ แล้วค่อย join('') รวมเป็นสตริง