แยกสตริงเป็นคำ (split by space) แล้วหาคำที่สั้นที่สุดและยาวที่สุด
ตัวอย่าง
"Hardships often prepare ordinary people for an extraordinary destiny" → ["an", "extraordinary"]
ตัวอย่างโค้ด
const str = 'Hardships often prepare ordinary people for an extraordinary destiny';
const largestSmallest = str => {
const words = str.split(' ');
let min = words[0], max = words[0];
for (let i = 1; i < words.length; i++) {
if (words[i].length < min.length) min = words[i];
if (words[i].length > max.length) max = words[i];
}
return [min, max];
};
console.log(largestSmallest(str));
ผลลัพธ์
[ 'an', 'extraordinary' ]
วิธีแบบ Functional (ES6+)
const largestSmallest = str => {
const words = str.split(' ');
return [
words.reduce((a, b) => a.length <= b.length ? a : b),
words.reduce((a, b) => a.length >= b.length ? a : b)
];
};
// หรือใช้ sort
const largestSmallest = str => {
const sorted = str.split(' ').sort((a, b) => a.length - b.length);
return [sorted[0], sorted[sorted.length - 1]];
};
เวอร์ชัน reduce ใช้ O(n) ส่วน sort ใช้ O(n log n)