ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์และคืนค่าอาร์เรย์อีกอันหนึ่ง โดยสมาชิกแรกคือค่าน้อยที่สุดของอาร์เรย์เข้า และสมาชิกที่สองคือค่ามากที่สุด
ตัวอย่าง
โค้ดตัวอย่างดังนี้:
const arr = [56, 34, 23, 687, 2, 56, 567];
const findMinMax = (arr = []) => {
const creds = arr.reduce((acc, val) => {
let [smallest, greatest] = acc;
if(val > greatest){
greatest = val;
};
if(val < smallest){
smallest = val;
};
return [smallest, greatest];
}, [Infinity, -Infinity]);
return creds;
};
console.log(findMinMax(arr));
ผลลัพธ์
[2, 687]