猿问

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

我有一个对象数组,我想从最近的对象中获取最接近的前一个 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));


Smart猫小萌
浏览 180回答 3
3回答

长风秋雁

我发现很容易扭转阵列和从切换比较>=到<=: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如果没有找到元素,这将返回。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答