I need to get the next lower object in an array using a weight value.
const data = [
{ weight: 1, size: 2.5 },
{ weight: 2, size: 3.0 },
{ weight: 4, size: 3.5 },
{ weight: 10, size: 4.0 },
{ weight: 20, size: 5.0 },
{ weight: 30, size: 6.0 }
]
If the weight is 19, I need to get the object { weight: 10, size: 4.0 }
.
With this attempt, I do get the closest object, but I always need to get the object with the next lowest value. If weight is smaller then 1, the first element should be returned.
const get_size = (data, to_find) =>
data.reduce(({weight}, {weight:w}) =>
Math.abs(to_find - w) < Math.abs(to_find - weight) ? {weight: w} : {weight}
)