Recep Selim Ağırman Recep Selim Ağırman - 6 months ago 32
Javascript Question

Get closest number of array

I want get closest number in the array. It have to be like this:


For example I have an array:

[1, 3, 7, 15, 40, 55, 70, 80, 95]




Number variable:
numberD1
;


If numberD1: 8 - The closest number can be only 7. Not 15.


If numberD1: 54 - It can be only 40. Not 55.



I mean, i want closest number like this. But what I selected the number mustn't be higher than the closest number(like
Math.floor()
function).

Sorry for my Bad English. I hope i told my problem as good.

Answer

You could use this:

// sample array
a = [1, 3, 7, 15, 40, 55, 70, 80, 95]

// get right number
function getClosest(a, numberD1) {
    return numberD1 - a.reduce(function(closest, v) {
        return numberD1 >= v ? Math.min(numberD1-v, closest) : closest;
    }, 1e100);
}  


// output result
document.write(8 + ' => ' + getClosest(a, 8));

document.write('<br>');

document.write(54 + ' => ' + getClosest(a, 54));

Comments