ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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