如何从javascript中的对象数组中获取最接近的先前id

我有一个对象数组,我想从最近的对象获得最接近的前一个id。我能够得到最接近的下一个id,它的工作正常但是以前不能正常工作。它直接取对象的第一个id。这是代码以下。任何人都可以帮助我。

JAVASCRIPT

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));


红颜莎娜
浏览 574回答 4
4回答

绝地无双

我发现更容易反转数组并将比较切换>=为<=:const findClosestNextId&nbsp; = (x, arr) =>&nbsp;&nbsp; (arr.find ( ({id}) => id >= x) || {} ) .idconst findClosestPrevId&nbsp; = (x, arr) =>&nbsp;&nbsp; (arr .slice(0) .reverse() .find ( ({id}) => id <= x) || {}) .idconst array = [{ id: 4 }, { id: 10 }, { id: 15 }];console .log (&nbsp; findClosestNextId (5,&nbsp; array), //=> 10&nbsp; findClosestNextId (11, array), //=> 15&nbsp; findClosestNextId (42, array), //=> undefined&nbsp; findClosestPrevId (5,&nbsp; array), //=> 4&nbsp; findClosestPrevId (11, array), //=> 10&nbsp; findClosestPrevId (2,&nbsp; array), //=> undefined)&nbsp;&nbsp;该slice电话有防止这种修改原始数组。undefined如果没有找到元素,这将返回。

MMTTMM

我对您的代码进行了一些更改,现在应该可以正常工作了。看一看。&nbsp; &nbsp; const array = [{id:3}, {id:4}, {id:10}, {id:15}];&nbsp; &nbsp; // you should order the list by id before you try to search, this incase you have not orginized list.&nbsp; &nbsp; // filter the list first and get the prev id to 5&nbsp;&nbsp; &nbsp; // you should get 3 and 4 then&nbsp;&nbsp; &nbsp; // slice(-1) to get the last element of the array which should be 4&nbsp; &nbsp; const findClosesPrevtId = (x) =>&nbsp; &nbsp; (array.filter(({id}) => id <= x ).slice(-1)[0] || {}).id;&nbsp; &nbsp; const findClosestNextId = (x) =>&nbsp;&nbsp; &nbsp; (array.filter(({id}) => id >= x )[0] || {}).id;&nbsp; &nbsp; console.log("Prev to 5:"+ findClosesPrevtId(5));&nbsp; &nbsp; console.log("Next to 11:" +findClosestNextId(11));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript