- 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
How to find a nearest higher number from a specific set of numbers: JavaScript ?
We have a set of numbers and our requirement is to find the same or the nearest higher number key to a specific number provided as the input to the function.
The set of numbers is defined as −
const numbers = { A:107, B:112, C:117, D:127, E:132, F:140, G:117, H:127, I:132, J:132, K:140, L:147, M:117, N:127, O:132 };
Example
The code for this will be −
const numbers = { A:107, B:112, C:117, D:127, E:132, F:140, G:117, H:127, I:132, J:132, K:140, L:147, M:117, N:127, O:132 }; const nearestHighest = (obj, val) => { let diff = Infinity; const nearest = Object.keys(obj).reduce((acc, key) => { let difference = obj[key] - val; if (difference >= 0 && difference < diff) { diff = difference; acc = [key]; } return acc; }, []) return nearest; }; console.log(nearestHighest(numbers, 140));
Output
And the output in the console will be −
['F']
- Related Articles
- Nearest Prime to a number - JavaScript
- Nearest power 2 of a number - JavaScript
- Program to find higher number with same number of set bits as n in Python?
- Finding nearest prime to a specified number in JavaScript
- Split a range of number to a specific number of intervals JavaScript
- Best way to find two numbers in an array whose sum is a specific number with JavaScript?
- Listing all the prime numbers upto a specific number in JavaScript
- Finding two prime numbers with a specific number gap in JavaScript
- How to get the value of a number rounded to the nearest integer in JavaScript?
- Clear/Set a specific bit of a number in Arduino
- How to use JavaScript to set cookies for a specific page only?
- How to retrieve a specific number of lines from files in PowerShell?
- How to generate random whole numbers in JavaScript in a specific range?
- Next higher number with same number of set bits in C++
- Round number down to nearest power of 10 JavaScript

Advertisements