我有一个对象数组,我想从最近的对象获取最近的前一个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));
答案 0 :(得分:2)
如果您使用x <= i
从左到右搜索,则第一个元素将充满find
。使用findLast
从右到左搜索。
不幸的是,我刚刚发现实际上还没有findLast
(有reduceRight
,lastIndexOf
...:/),所以您必须自己编写: / p>
Object.defineProperty(Array.prototype, "findLast", {
value(cb, context) {
for(let i = this.length - 1; i >= 0; i--)
if(cb.call(context, this[i], i, this))
return this[i];
}
});
const findClosesPrevtId = (x) => ( array.findLast( ({id}) => x <= id ) || {} ).id;
答案 1 :(得分:0)
我对您的代码进行了一些更改,现在应该可以使用了。 看看。
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));
答案 2 :(得分:0)
如果id
大于所需ID,则可以存储贵重/ next元素并停止迭代。
const
closestPrevious = id => {
var last = {};
array.some(o => o.id > id || (last = o, false))
return last.id;
},
closestNext = id => {
var next = array[0];
array.some((o, i, { [i + 1]: n = {} }) => o.id > id || (next = n, false))
return next.id;
},
array = [{ id: 4 }, { id: 10 }, { id: 15 }];
console.log(closestNext(5)); // 10
console.log(closestNext(11)); // 15
console.log(closestPrevious(5)); // 4
console.log(closestPrevious(11)); // 10
答案 3 :(得分:0)
我发现更容易反转数组并将比较从>=
切换到<=
:
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
。