简体   繁体   中英

How to get closest previous id from array of object in javascript

I have an array of object,I want to get the closest previous id from nearest object.I can able to get closest next id,its working fine but for previous is not working.Its taking direct first id of object.Here is the code below.Can anyone please help me on it.

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

Cause x <= i will be fullfilled for the first element if you use find to search from left to right. Use findLast to search from right to left.

Unfortunately I just found out that there is actually not a findLast yet (there is reduceRight , lastIndexOf ... :/), so you have to write it yourself:

  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;

I made some changes to your code and it should work now. Have a look.

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

You could store the precious/next element and stop the iteration if id is greater than the wanted id.

 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 

I find it easier to reverse the array and switch the comparison from >= to <= :

 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 ) 

The slice call is there to prevent this from modifying the original array. This will return undefined if there is no element found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM