JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
JavaScript
const data = [
{ 'time': 1638360813000, 'path': '/api/path/videoSession1' },
{ 'time': 1638360814000, 'path': '/api/path/videoSession2' },
{ 'time': 1638360815000, 'path': '/api/path/videoSession3' },
{ 'time': 1638360816000, 'path': '/api/path/videoSession4' },
{ 'time': 1638360817000, 'path': '/api/path/videoSession5' },
{ 'time': 1638360818000, 'path': '/api/path/videoSession6' },
{ 'time': 1638360819000, 'path': '/api/path/videoSession7' }
];
// Convert the array to a Map with time as key and path as value
const dataMap = new Map(data.map(item => [item.time, item.path]));
// Function to find the closest time in the Map
function findClosestTime(currentTime) {
const closestTime = [...dataMap.keys()].find(time => time > currentTime);
if (closestTime !== undefined) {
return { time: closestTime, path: dataMap.get(closestTime) };
}
// Handle the case where no time is greater than the provided time
return null;
}
// Example usage
const currentTime = 1638360814500; // Replace with your current time
const closestData = findClosestTime(currentTime);
if (closestData !== null) {
console.log(`Closest time: ${closestData.time}, Path: ${closestData.path}`);
} else {
console.log('No time greater than the provided time');
}