4 回答
TA贡献1946条经验 获得超4个赞
我发现更容易反转数组并将比较切换>=为<=:
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如果没有找到元素,这将返回。
TA贡献1869条经验 获得超4个赞
我对您的代码进行了一些更改,现在应该可以正常工作了。看一看。
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));
添加回答
举报