เรามีอาร์เรย์ของตัวอักษรสตริงเช่นนี้ −
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' }