Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
};
Algorithm Approach
The solution uses the reduce() method to iterate through the object keys and find the key(s) with the smallest non-negative difference from the target value. This ensures we get the nearest higher or equal number.
Example
Here's the complete implementation:
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));
console.log(nearestHighest(numbers, 130));
console.log(nearestHighest(numbers, 120));
Output
['F'] ['E'] ['D']
How It Works
The function works by:
-
Initialize: Set
difftoInfinityto track the smallest difference -
Iterate: Loop through all object keys using
reduce() - Calculate: Find the difference between each value and the target
- Filter: Only consider non-negative differences (same or higher numbers)
- Update: Keep track of keys with the smallest valid difference
Handling Multiple Matches
If multiple keys have the same nearest higher value, the function returns all matching keys:
// Both F and K have value 140 console.log(nearestHighest(numbers, 140)); // Multiple keys with value 132 (E, I, J, O) console.log(nearestHighest(numbers, 130));
['F'] ['E']
Conclusion
This approach efficiently finds the nearest higher number using reduce() to iterate once through the object. The function returns an array of keys, making it useful when multiple keys share the same nearest higher value.
