为了账号安全,请及时绑定邮箱和手机立即绑定

如何从javascript中的对象数组中获取最接近的先前ID

如何从javascript中的对象数组中获取最接近的先前ID

Smart猫小萌 2021-06-01 14:38:02
我有一个对象数组,我想从最近的对象中获取最接近的前一个 id。我可以得到最接近的下一个 id,它工作正常,但前一个不起作用。它直接采用对象的第一个 id。这是代码下面。任何人都可以帮我解决这个问题。爪哇脚本const array = [{id:4}, {id:10}, {id:15}];const findClosesPrevtId = (x) => ( array.find( ({id}) => x <= id ) || {} ).id;const findClosestNextId = (x) => ( array.find( ({id}) => x >= id ) || {} ).id;console.log(findClosesPrevtId(5));console.log(findClosestNextId(11));
查看完整描述

3 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

我发现很容易扭转阵列和从切换比较>=到<=:


const findClosestNextId  = (x, arr) => 

  (arr.find ( ({id}) => id >= x) || {} ) .id


const findClosestPrevId  = (x, arr) => 

  (arr .slice(0) .reverse() .find ( ({id}) => id <= x) || {}) .id


const array = [{ id: 4 }, { id: 10 }, { id: 15 }];


console .log (

  findClosestNextId (5,  array), //=> 10

  findClosestNextId (11, array), //=> 15

  findClosestNextId (42, array), //=> undefined


  findClosestPrevId (5,  array), //=> 4

  findClosestPrevId (11, array), //=> 10

  findClosestPrevId (2,  array), //=> undefined

)  

slice电话有防止这种修改原始数组。undefined如果没有找到元素,这将返回。


查看完整回答
反对 回复 2021-06-03
  • 3 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信