js数组查找最接近_如何从javascript中的对象数组中获取最接近的先前id

我对您的代码进行了一些更改,现在应该可以正常工作了。看一看。

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

// you should order the list by id before you try to search, this incase you have not orginized list.

// filter the list first and get the prev id to 5

// you should get 3 and 4 then

// slice(-1) to get the last element of the array which should be 4

const findClosesPrevtId = (x) =>

(array.filter(({id}) => id <= x ).slice(-1)[0] || {}).id;

const findClosestNextId = (x) =>

(array.filter(({id}) => id >= x )[0] || {}).id;

console.log("Prev to 5:"+ findClosesPrevtId(5));

console.log("Next to 11:" +findClosestNextId(11));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值