Find object in array with next lower value

我的梦境 提交于 2019-12-19 10:45:37

问题


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)



来源:https://stackoverflow.com/questions/59301021/find-object-in-array-with-next-lower-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!