
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 Closest Value in an Array using JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument. The function should then return the number from the array which closest to the number given to the function as second argument.
Example
The code for this will be −
const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3]; const num = 37 const findClosest = (arr, num) => { const creds = arr.reduce((acc, val, ind) => { let { diff, index } = acc; const difference = Math.abs(val - num); if(difference < diff){ diff = difference; index = ind; }; return { diff, index }; }, { diff: Infinity, index: -1 }); return arr[creds.index]; }; console.log(findClosest(arr, num));
Output
The output in the console −
45
Advertisements