- 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
Get the closest number out of an array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a single number as the second argument.
The function should find and return that number from the array which is closest to the number specified by the second argument.
For example −
const arr = [34, 67, 31, 53, 89, 12, 4]; const num = 41;
Then the output should be 34.
Example
Following is the code −
const arr = [34, 67, 31, 53, 89, 12, 4]; const num = 41; const findClosest = (arr = [], num) => { let curr = arr[0]; let diff = Math.abs (num - curr); for (let val = 0; val < arr.length; val++) { let newdiff = Math.abs (num - arr[val]); if (newdiff < diff) { diff = newdiff; curr = arr[val]; }; }; return curr; }; console.log(findClosest(arr, num));
Output
Following is the output on console −
34
Advertisements