
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 the closest value 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 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
- Related Questions & Answers
- Find closest index of array in JavaScript
- Find the closest index to given value in JavaScript
- Get the closest number out of an array in JavaScript
- How to find the maximum value of an array in JavaScript?
- How to find the minimum value of an array in JavaScript?
- Find closest value for every element in array in C++
- C++ Program to Find Closest Pair of Points in an Array
- Find closest greater value for every element in array in C++
- Find closest smaller value for every element in array in C++
- Find k closest numbers in an unsorted array in C++
- Get closest number out of array JavaScript
- Find indexes of multiple minimum value in an array in JavaScript
- Find closest number in array in C++
- Find the number of times a value of an object property occurs in an array with JavaScript?
- How to find the value closest to positive infinity in Python?
Advertisements