เราต้องเขียนฟังก์ชันที่รับสตริงและคืนค่าคำที่สั้นที่สุดจากสตริง
ตัวอย่าง: หากสตริงนำเข้าคือ:
const str = 'This is a sample string';
ผลลัพธ์ควรเป็น:
const output = 'a';
ตัวอย่าง
โค้ดสำหรับนี้:
const str = 'This is a sample string'; const findSmallest = str => { const strArr = str.split(' '); const creds = strArr.reduce((acc, val) => { let { length, word } = acc; if(val.length < length){ length = val.length; word = val; }; return { length, word }; }, { length: Infinity, word: '' }); return creds.word; }; console.log(findSmallest(str));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
a