โจทย์
รวม array elements เป็น string โดยข้าม null/undefined values
Input: ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"]
ตัวอย่างโค้ด
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];
const joinArray = arr => {
const sentence = arr.reduce((acc, val) => {
return acc + (val || "");
}, "");
return sentence;
};
console.log(joinArray(arr));
ผลลัพธ์
Hereisanexampleofasentence
คำอธิบาย
reduce สะสม stringval || "" ใช้ short-circuit evaluation: null, undefined, 0, "" → falsy → ใช้ "" แทน
ค่า truthy ("Here", "is", "an", "example", "of", "a", "sentence") ถูกต่อกัน
หมายเหตุ: 0 และ "" ก็ถูกข้ามด้วย เพราะเป็น falsy