My approach to solving this problem differs from what has been shared here previously. While it may be slightly longer, I believe it offers a clearer explanation of the logic behind the code. The functionality has been verified and you can see the results in the provided fiddle. Below is the code snippet:
var times = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM",
"03:00 AM", "07:00 AM", "06:00 PM"];
//Sort the array
times.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
//Test Sorted Array
console.log(times);
var testTime = "05:00 PM";
function findNearestTime(times, currentTime) {
//Copy given array to new array
var allTimes = times.slice();
//Push current time to new arrray
allTimes.push(currentTime);
//Sort New array
allTimes.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
//Nearest time will be either the item to the left or to the right of currentTime since array is sorted
//Now we just find which one is the closest
var indexOfCurrent = allTimes.indexOf(currentTime);
if (indexOfCurrent == 0) { //if current is first element, nearest will be item
//after first element
return allTimes.slice(indexOfCurrent + 1, indexOfCurrent + 2 );
}else if (indexOfCurrent == allTimes.length - 1) { //current is last one,
//nearest will be the item before current
return allTimes.slice(allTimes.length - 2, indexOfCurrent);
}else { //if neither case above, this is where magic happens
//Find the diff between left/right adjacent element and the current element in the new sorted array
var currTime = new Date("01/01/2018 " + currentTime).getHours();
var currTimeLower = new Date("01/01/2018 " + allTimes.slice(indexOfCurrent - 1,
indexOfCurrent)).getHours();
var currTimeUpper = new Date("01/01/2018 " + allTimes.slice(indexOfCurrent + 1,
indexOfCurrent + 2)).getHours();
var leftDiff = currTime - currTimeLower;
var rightDiff = currTimeUpper - currTime;
if(leftDiff < rightDiff) {
return allTimes.slice(indexOfCurrent - 1, indexOfCurrent);
}
else {
return allTimes.slice(indexOfCurrent + 1, indexOfCurrent + 2);
}
};
}
console.log(findNearestTime(times, testTime));
To view the working example along with different test cases, please refer to the following fiddle link:
https://jsfiddle.net/b36fxpqr/13/