[英]How to get closest previous id from array of object in javascript
我有一個對象數組,我想從最近的對象獲取最近的前一個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));
原因x <= i
將fullfilled為第一要素,如果你使用find
搜索由左到右。 使用findLast
從右到左搜索。
不幸的是,我發現實際上還沒有findLast
(存在reduceRight
, lastIndexOf
...:/),因此您必須自己編寫:
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;
我對您的代碼進行了一些更改,現在應該可以使用了。 看一看。
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));
如果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
我發現更容易反轉數組並將比較從>=
切換到<=
:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.