0

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

Antony
  • 970
  • 3
  • 20
  • 46
  • @CertainPerformance – Antony Jun 12 '19 at 09:22
  • @Nina Scholz Thanks for marking my question as duplicate and down voting. Your duplicate reference is old from '12 and it is for normal date format, not for epoch time format. Yes I agree that the solution in duplicate reference may resolve the question asked by me. – Antony Jun 12 '19 at 09:24
  • @Tibrogargan The solution I received for my question is updated and more tedious which uses latest functionalities like arrow function. Still you want me to write my code with the lengthy solution provided in 2012, yes I agree that you did right thing OR you should have updated the duplicate reference with the latest solution and mark my question as a duplicate one. Please dont be hurry to mark as duplicate, take time to act. – Antony Jun 12 '19 at 09:25

1 Answers1

1

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);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62