Find object in array with next lower value

2020-03-30 07:53发布

问题:

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}
  )

回答1:

If the objects' weights are in order, like in the question, one option is to iterate from the end of the array instead. The first object that matches will be what you want.

If the .find below doesn't return anything, alternate with || data[0] to get the first item in the array:

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 }
]

const output = data.reverse().find(({ weight }) => weight < 19) || data[0];
console.log(output);

(if you don't want to mutate data, you can .slice it first)