Finding closest number in an array of objects [closed]

You could take a check for the smaller absolute delta of the value and the wanted value and return the object with the smaller one.

For getting a smaller value than the pivot add another check in front of the absolute check.

var data = [{ id: 1, time_in: 2 }, { id: 4, time_in: 10 }, { id: 4, time_in: 6 }, { id: 4, time_in: 25 }, { id: 4, time_in: 14 }],
    pivot = 17,
    result = data.reduce((a, b) => 
        a.time_in <= pivot && Math.abs(a.time_in - pivot) < Math.abs(b.time_in - pivot)
            ? a
            : b
    );

console.log(result);

Leave a Comment