Dev Helpers
← Back

Find the nearest timestamp

Find the nearest timestamp using TypeScript.

Open this example in the interactive library

Source code

type Sample = { time: number; value: number };
const samples: Sample[] = [
  { time: 1, value: 2 },
  { time: 2, value: 6 },
  { time: 4, value: 10 },
];
console.log(
  samples.reduce((best, s) =>
    Math.abs(s.time - 3.8) < Math.abs(best.time - 3.8) ? s : best,
  ),
);

Sample output

{ time: 4, value: 10 }