- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find closest index of array in JavaScript
Suppose, we have an array like this −
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
We are required to write a JavaScript function that takes in one such array and a number, say n.
The function should return the index of item from the array which is closest to the number n.
Example
Following is the code −
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));
Output
This will produce the following output on console −
4
- Related Articles
- Index of closest element in JavaScript
- Find the closest index to given value in JavaScript
- Find the closest value of an array in JavaScript
- Get closest number out of array JavaScript
- Find closest number in array in C++
- Get the closest number out of an array in JavaScript
- Finding median index of array in JavaScript
- C++ Program to Find Closest Pair of Points in an Array
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Reverse index value sum of array in JavaScript
- Sort by index of an array in JavaScript
- Find closest value for every element in array in C++
- Find k closest numbers in an unsorted array in C++
- How can I find the index of a 2d array of objects in JavaScript?
- Program to find list that shows closest distance of character c from that index in Python

Advertisements