I am trying to find the nearest element in an array based on a given value, but I specifically want it to be the nearest one that is greater than or equal to the value. For example, if I have an array like [3000, 5000, 8000], when I search for a number below or equal to 3000, it should return 3000. However, if I search for 3001, it should return 5000 instead.
This is the code I currently have:
let array = [3000, 5000, 8000];
function closestNumArray(array, num) {
var x = array.reduce(function(min, max) {
return (Math.abs(max - num) < Math.abs(min - num) ? max : min);
});
return x;
}
closesNumArray(array, 3001) // returns 3000
I would like it to return 5000, or the nearest next element based on the value, but it currently returns 3000.
Thank you!