使用 JavaScript 在数组中查找最近的日期 [英] Find closest date in array with JavaScript

查看:20
本文介绍了使用 JavaScript 在数组中查找最近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含天数的数组.每一天都是一个对象,例如:

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

  • 2012 年 8 月 2 日
  • 2012 年 8 月 4 日
  • 2012 年 8 月 23 日

我搜索 2012 年 8 月 11 日,我希望它返回 2012 年 8 月 4 日和 2012 年 8 月 23 日.

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];
}

然而,这会返回unidentified.

实现这一目标的最有效(最少处理器/内存密集型方式)是什么?

What would be the most efficient (least processor/memory intensive way) to achieve this?

但是,这些结果如何奇怪"?您能提供一个代码和数据示例吗?"

我现在使用以下内容来生成日期数组:

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()});
}

奇怪的部分是,使用下面的代码,这仅适用于 10 个日期或更短的数组.每当我使用 11 个或更多日期的数组时,结果就会出乎意料.

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 or more dates, the results become unexpected.

例如:使用 15 个日期的数组,从 2012 年 8 月 6 日到 2012 年 8 月 21 日.如果我然后调用 findClosest(full_day_array, new Date("30/07/2012"); 你会期望它返回 {nextIndex: 0, prevIndex: -1}.然而,它返回 {nextIndex: 7, prevIndex: -1}.为什么?

For instance: using an array of 15 dates, starting on August 6, 2012, to August 21, 2012. If I then call findClosest(full_day_array, new Date("30/07/2012"); you would expect it to return {nextIndex: 0, prevIndex: -1}. However, it returns {nextIndex: 7, prevIndex: -1}. Why?

function findClosest(objects, testDate) {
    var 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]; });


    var nextIndex;
    var prevIndex;

    if(nextDateIndexesByDiff.length < 1) {
        nextIndex = -1;
    } else {
        nextIndex = nextDateIndexesByDiff[0][0];
    }
    if(prevDateIndexesByDiff.length < 1) {
        prevIndex = -1;
    } else {    
        prevIndex = prevDateIndexesByDiff[0][0];
    }
    return {nextIndex: nextIndex, prevIndex: prevIndex};
}

推荐答案

无论日期数组有多长,这都有效:

This works, no matter how long the array of dates is:

function newFindClosest(dates, testDate) {
    var before = [];
    var after = [];
    var max = dates.length;
    for(var i = 0; i < max; i++) {
        var tar = dates[i];
        var arrDate = new Date(tar.day_year, tar.day_month, tar.day_number);
        // 3600 * 24 * 1000 = calculating milliseconds to days, for clarity.
        var diff = (arrDate - testDate) / (3600 * 24 * 1000);
        if(diff > 0) {
            before.push({diff: diff, index: i});
        } else {
            after.push({diff: diff, index: i});
        }
    }
    before.sort(function(a, b) {
        if(a.diff < b.diff) {
            return -1;
        }
        if(a.diff > b.diff) {
            return 1;
        }
        return 0;
    });

    after.sort(function(a, b) {
        if(a.diff > b.diff) {
            return -1;
        }
        if(a.diff < b.diff) {
            return 1;
        }
        return 0;
    });
    return {datesBefore: before, datesAfter: after};
}

这篇关于使用 JavaScript 在数组中查找最近的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆