ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีตัวเลขคั่นด้วยช่องว่าง ฟังก์ชันควรคืนค่าสตริงที่มีเฉพาะตัวเลขมากที่สุดและน้อยที่สุด คั่นด้วยช่องว่าง
อินพุต
const str = '5 57 23 23 7 2 78 6';
เอาต์พุต
const output = '78 2';
เพราะ 78 เป็นตัวเลขมากที่สุด และ 2 เป็นตัวเลขน้อยที่สุด
ตัวอย่าง
โค้ดตัวอย่างดังนี้:
const str = '5 57 23 23 7 2 78 6';
const pickGreatestAndSmallest = (str = '') => {
const strArr = str.split(' ');
let creds = strArr.reduce((acc, val) => {
let { greatest, smallest } = acc;
greatest = Math.max(val, greatest);
smallest = Math.min(val, smallest);
return { greatest, smallest };
}, {
greatest: -Infinity,
smallest: Infinity
});
return `${creds.greatest} ${creds.smallest}`;
};
console.log(pickGreatestAndSmallest(str));
ผลลัพธ์
78 2