I have a base epoch time value and an array of epoch time and value at corresponding epoch time.
I have to get value of the epoch time from array such a way that the epoch time in the array should be equal to or nearest highest value less than the base epoch time.
Is there any function to sort out this task?
Below is the base epoch time:
1557302199295
Below is the array of epoch time with values.
[ { stime: 1557302193273, value: 3.799999952316284 }, { stime: 1557302243474, value: 6.900000095367432 }, { stime: 1557302205317, value: 6.099999904632568 }, { stime: 1557302194874, value: 1.899999976158142 }, { stime: 1557302208963, value: 8.199999809265137 }, { stime: 1557302199295, value: 2.200000047683716 }, { stime: 1557302193273, value: 3.799999952316284 } , { stime: 1557302243474, value: 6.900000095367432 }, { stime: 1557302205317, value: 6.099999904632568 }, { stime: 1557302194874, value: 1.899999976158142 }, { stime: 1557302208963, value: 8.199999809265137 }, { stime: 1557302199295, value: 2.200000047683716 } ]
I have to know how to find out the highest nearest epoch time to the base epoch time from array
You can sort your array and filter first item greater than the value.
const getFirst = (arr, predicate) => {
for (const val of arr) {
if (predicate(val)) return val;
}
return undefined;
}
var arr = [ { stime: 1557302193273, value: 3.799999952316284 }, { stime: 1557302243474, value: 6.900000095367432 }, { stime: 1557302205317, value: 6.099999904632568 }, { stime: 1557302194874, value: 1.899999976158142 }, { stime: 1557302208963, value: 8.199999809265137 }, { stime: 1557302199295, value: 2.200000047683716 }, { stime: 1557302193273, value: 3.799999952316284 } , { stime: 1557302243474, value: 6.900000095367432 }, { stime: 1557302205317, value: 6.099999904632568 }, { stime: 1557302194874, value: 1.899999976158142 }, { stime: 1557302208963, value: 8.199999809265137 }, { stime: 1557302199295, value: 2.200000047683716 } ];
const x = getFirst(arr.sort((a, b) => a.stime - b.stime), x => x.stime > 1557302199295);
console.log(x);