Home > Net >  find an object with the latest timestamp string that is earlier than a reference value in an array
find an object with the latest timestamp string that is earlier than a reference value in an array

Time:09-16

I have the following code to go through an array of objects and find the object with a timestamp that is still smaller of a reference value but the biggest of those

    for (const elem of objs) {
        if (elem._time >= failureTime) {//we are one too far
            break;          
        } else {
            temp = elem; //this will end up as the last element with timestamp before event
           }
        }           

This assumes that objs is ordered by timestamp, which I can't predict so I need to reorder it every time. I tried to create a .reduce function to solve that but horribly failed. Is there a way to do it?

CodePudding user response:

If you're asking how to find the largest time less than failureTime when objs isn't sorted, you just don't stop when you see an out-of-range value. Instead, you ignore those, and keep track of the highest in-range value you've seen:

let temp = null;
for (const elem of objs) {
    if (elem._time < failureTime && (temp === null || elem._time > temp._time)) {
        temp = elem;
    }
}

Live Example:

const objs = [
    { _time: new Date("2022-01-02T00:00:00.000Z") },
    { _time: new Date("2022-01-04T00:00:00.000Z") },
    { _time: new Date("2022-01-03T00:00:00.000Z") },
    { _time: new Date("2022-01-06T00:00:00.000Z") },
    { _time: new Date("2022-01-01T00:00:00.000Z") },
];
const failureTime = new Date("2022-01-05T00:00:00.000Z");
let temp = null;
for (const elem of objs) {
    if (elem._time < failureTime && (temp === null || elem._time > temp._time)) {
        temp = elem;
    }
}
console.log(temp._time);

CodePudding user response:

You can use the reduce method;

//failureTime
arr.reduce((acc,key)=>{
if(acc._time <= failureTime){
 if(acc._time < key._time) return key;
 else return acc;
} 
},arr[0]);

Hope it helps.

  • Related