![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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