เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลขและส่งกลับอาร์เรย์ย่อยของสององค์ประกอบจากอาร์เรย์ดั้งเดิมซึ่งผลรวมใกล้เคียงกับ 0 มากที่สุด
หากความยาวของอาร์เรย์น้อยกว่า 2 เราควรคืนค่าอาร์เรย์ทั้งหมด
ตัวอย่างเช่น หากอาร์เรย์อินพุตเป็น −
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
ในที่นี้ ผลรวมของคู่ [5, -4] คือ 1 ซึ่งเป็น 0 ที่ใกล้ที่สุดสำหรับสององค์ประกอบที่อยู่ติดกันของอาร์เรย์ ดังนั้นเราควรคืนค่า [5, -4]
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
const closestElements = (arr, sum) => {
if(arr.length <= 2){
return arr;
}
const creds = arr.reduce((acc, val, ind) => {
let { closest, startIndex } = acc;
const next = arr[ind+1];
if(!next){
return acc;
}
const diff = Math.abs(sum - (val + next));
if(diff < closest){
startIndex = ind;
closest = diff;
};
return { startIndex, closest };
}, {
closest: Infinity,
startIndex: -1
});
const { startIndex: s } = creds;
return [arr[s], arr[s+1]];
};
console.log(closestElements(arr, 1)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
[5, -4]