我有一个对象数组,我想从最近的对象中获取最接近的前一个 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
如果没有找到元素,这将返回。
添加回答
举报
0/150
提交
取消