Viết hàm nhận câu, trả về độ dài của từ có độ dài nhỏ thứ 2.
Ví dụ
Chuỗi: 'This is a sample string'
Độ dài các từ: 4, 2, 1, 6, 6 → sắp xếp: 1, 2, 4, 6, 6 → nhỏ thứ 2 = 2
Giải pháp
Mã triển khai:
const str = 'This is a sample string';
const secondSmallest = str => {
const words = str.split(' ');
if (words.length < 2) return false;
const lengths = words.map(w => w.length).sort((a, b) => a - b);
return lengths[1];
};
console.log(secondSmallest(str));
Kết quả
Đầu ra trong console:
2