在数组中查找下一个较低的值的对象 [英] Find object in array with next lower value

查看:98
本文介绍了在数组中查找下一个较低的值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用权重值获取数组中的下一个下层对象.

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

如果权重为19,则需要获取对象{ weight: 10, size: 4.0 }.

If the weight is 19, I need to get the object { weight: 10, size: 4.0 }.

通过这种尝试,我确实获得了最接近的对象,但是我总是需要获得具有下一个最低值的对象.如果权重小于1,则应返回第一个元素.

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

推荐答案

如果对象的权重是正确的,就像在问题中那样,则一种选择是从数组的末尾进行迭代.匹配的第一个对象就是您想要的.

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.

如果下面的.find没有返回任何内容,请与|| data[0]交替显示以获取数组中的第一项:

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

(如果您不想变异data,则可以先.slice对其进行修改)

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

这篇关于在数组中查找下一个较低的值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆