Find closest date in array with JavaScript
If you use an array of Date
objects instead of your self-defined structure it can be achieved very easily in O(N):
var testDate = new Date(...);
var bestDate = days.length;
var bestDiff = -(new Date(0,0,0)).valueOf();
var currDiff = 0;
var i;
for(i = 0; i < days.length; ++i){
currDiff = Math.abs(days[i] - testDate);
if(currDiff < bestDiff){
bestDate = i;
bestDiff = currDiff;
}
}
/* the best date will be days[bestDate] */
If the array is sorted it can be achieved in O(log N) with binary search.
Edit: "it is crucial that I find both the closest match before and after the date"
var testDate = new Date(...);
var bestPrevDate = days.length;
var bestNextDate = days.length;
var max_date_value = Math.abs((new Date(0,0,0)).valueOf());
var bestPrevDiff = max_date_value;
var bestNextDiff = -max_date_value;
var currDiff = 0;
var i;
for(i = 0; i < days.length; ++i){
currDiff = testDate - days[i].the_date_object;
if(currDiff < 0 && currDiff > bestNextDiff){
// If currDiff is negative, then testDate is more in the past than days[i].
// This means, that from testDate's point of view, days[i] is in the future
// and thus by a candidate for the next date.
bestNextDate = i;
bestNextDiff = currDiff;
}
if(currDiff > 0 && currDiff < bestPrevDiff){
// If currDiff is positive, then testDate is more in the future than days[i].
// This means, that from testDate's point of view, days[i] is in the past
// and thus by a candidate for the previous date.
bestPrevDate = i;
bestPrevDiff = currDiff;
}
}
/* days[bestPrevDate] is the best previous date,
days[bestNextDate] is the best next date */
Zeta's answer is excellent, but I was interested in how you'd approach this if you wanted to know the nearest N objects in either direction. Here's my stab:
var objects = [
{ day_year: "2012",
day_month: "08",
day_number: "02"
},
{ day_year: "2012",
day_month: "08",
day_number: "04"
},
{ day_year: "2012",
day_month: "08",
day_number: "23"
}
];
var testDate = new Date('08/11/2012'),
nextDateIndexesByDiff = [],
prevDateIndexesByDiff = [];
for(var i = 0; i < objects.length; i++) {
var thisDateStr = [objects[i].day_month, objects[i].day_number, objects[i].day_year].join('/'),
thisDate = new Date(thisDateStr),
curDiff = testDate - thisDate;
curDiff < 0
? nextDateIndexesByDiff.push([i, curDiff])
: prevDateIndexesByDiff.push([i, curDiff]);
}
nextDateIndexesByDiff.sort(function(a, b) { return a[1] < b[1]; });
prevDateIndexesByDiff.sort(function(a, b) { return a[1] > b[1]; });
console.log(['closest future date', objects[nextDateIndexesByDiff[0][0]]]);
console.log(['closest past date', objects[prevDateIndexesByDiff[0][0]]]);
You can easily use the sort
function with a custom comparator function:
// assuming you have an array of Date objects - everything else is crap:
var arr = [new Date(2012, 7, 1), new Date(2012, 7, 4), new Date(2012, 7, 5), new Date(2013, 2, 20)];
var diffdate = new Date(2012, 7, 11);
arr.sort(function(a, b) {
var distancea = Math.abs(diffdate - a);
var distanceb = Math.abs(diffdate - b);
return distancea - distanceb; // sort a before b when the distance is smaller
});
// result:
[2012-08-05, 2012-08-04, 2012-08-01, 2013-03-20]
To get only results before or after the diffdate
, you can filter the array for that:
var beforedates = arr.filter(function(d) {
return d - diffdate < 0;
}),
afterdates = arr.filter(function(d) {
return d - diffdate > 0;
});
If you have your custom array with the {the_date_object: new Date(...)}
objects, you will need to adapt the sort algorithm with
var distancea = Math.abs(diffdate - a.the_date_object);
var distanceb = Math.abs(diffdate - b.the_date_object);