KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have an array with days in it. Each day is an object, for example: {day_year: "2012", day_month: "08", day_number: "03", day_name: "mon"} I have also added a timestamp attribute to each day object, by using: function convertDays() { var max_i = days.length; for(var i = 0; i < max_i; i++) { var tar_i = days[i]; tar_i.timestamp = new Date(tar_i.day_year, tar_i.day_month, tar_i.day_number); } } The days in the array are arbitrary, so there is no real logic to them. Now I want to find the two closest days to any given date. So if the array with days contains August 2, 2012 August 4, 2012 August 23, 2012 And I search for August 11, 2012, I want it to return August 4, 2012 and August 23, 2012. I have tried using an answer from another question, that looks like this: function findClosest(a, x) { var lo, hi; for(var i = a.length; i--;) { if(a[i] <= x && (lo === undefined || lo < a[i])) lo = a[i]; if(a[i] >= x && (hi === undefined || hi > a[i])) hi = a[i]; } return [lo, hi]; } However, this returns unidentified . What would be the most efficient (least processor/memory intensive way) to achieve this? Edit: "However, how are those results "strange"? Could you provide an example of your code and data?" I'm now using the following to generate an array of dates: var full_day_array = []; for(var i = 0; i < 10; i++) { var d = new Date(); d.setDate(d.getDate() + i); full_day_array.push({day_year: d.getFullYear().toString(), day_month: (d.getMonth() + 1).toString(), day_number: d.getDate().toString()}); } The strange part is, using the code below, this only works for an array of 10 dates or shorter. Whenever I use an array of 11
Tags (comma-separated)
Save Edits
Cancel