- 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
Index of closest element 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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
4
- Related Articles
- Find closest index of array in JavaScript
- Closest Pair to Kth index element in Tuple using Python
- Find the closest index to given value in JavaScript
- Common element with least index sum in JavaScript
- Inserting element at falsy index in an array - JavaScript
- Get closest number out of array JavaScript
- Find the closest value of an array in JavaScript
- Find closest value for every element in array in C++
- Find the closest element in Binary Search Tree in C++
- Get the closest number out of an array in JavaScript
- Python – Negative index of Element in List
- Write a program to find the index of particular element in an array in javascript?
- Find closest greater value for every element in array in C++
- Find closest smaller value for every element in array in C++
- Finding the nth power of array element present at nth index using JavaScript

Advertisements