เรามีอาร์เรย์ของสตริงแบบนี้
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.'];
เราต้องเขียนฟังก์ชันที่คืนค่าคำที่ยาวที่สุดและสั้นที่สุดจากอาร์เรย์นี้ เราจะใช้ Array.prototype.reduce() เพื่อติดตามคำที่ยาวที่สุดและสั้นที่สุดในอาร์เรย์ตลอดการวนลูป
โค้ดสำหรับนี้จะเป็น
ตัวอย่าง
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.']; const findWords = (arr) => { return arr.reduce((acc, val) => { const { length: len } = val; if(len > acc['longest']['length']){ acc['longest'] = val; }else if(len < acc['shortest']['length']){ acc['shortest'] = val; }; return acc; }, { longest: arr[0], shortest: arr[0] }); }; console.log(findWords(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
{ longest: 'sentence.', shortest: 'a' }