สมมติว่าเรามีอาร์เรย์ดังนี้:
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์แบบนี้และตัวเลขหนึ่งตัว (เช่น n) ฟังก์ชันควรคืนค่าดัชนีขององค์ประกอบในอาร์เรย์ที่มีค่าใกล้เคียงกับตัวเลข n มากที่สุด
ตัวอย่าง
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
const closestIndex = (num, arr) => {
let curr = arr[0], diff = Math.abs(num - curr);
let index = 0;
for (let val = 0; val < arr.length; val++) {
let newdiff = Math.abs(num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
index = val;
}
}
return index;
};
console.log(closestIndex(150, arr));
ผลลัพธ์
โค้ดนี้จะแสดงผลลัพธ์ดังต่อไปนี้บนคอนโซล:
4