เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและส่งกลับคำที่สั้นที่สุดจากสตริง
ตัวอย่างเช่น หากสตริงอินพุตคือ −
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