4 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
我發(fā)現(xiàn)更容易反轉(zhuǎn)數(shù)組并將比較切換>=為<=:
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電話有防止這種修改原始數(shù)組。undefined如果沒有找到元素,這將返回。

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
我對(duì)您的代碼進(jìn)行了一些更改,現(xiàn)在應(yīng)該可以正常工作了??匆豢?。
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));
添加回答
舉報(bào)