 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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 the closest index to given value in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first input and a single number as the second input.
The function should find and return the index of the number from the array which is closest to the number specified by second argument.
Example
The code for this will be −
const arr = [0, 65, 131, 196, 259, 323, 388, 453, 517]; const target = 425; const findClosest = (arr, target) => {    let min;    let chosen = 0;    for (let i in arr) {       min = Math.abs(arr[chosen] − target);       if (Math.abs(arr[i] − target) < min) {          chosen = i;       };    };    return chosen; }; console.log(findClosest(arr, target));  Output
And the output in the console will be −
7
Advertisements
 